iobroker.javascript 9.0.11 → 9.0.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -5
- package/admin/assets/OpenAiDialog-BmcYPsVa.js +36 -0
- package/admin/assets/{Save--0ldNXLf.js → Save-DXaUpIPM.js} +1 -1
- package/admin/assets/{ScriptEditor-CpRWvDSw.js → ScriptEditor-BoSBgnK-.js} +1 -1
- package/admin/assets/{ScriptEditorVanillaMonaco-BWe9MiKn.js → ScriptEditorVanillaMonaco-Xge2wqgO.js} +1 -1
- package/admin/assets/{createSvgIcon-C_ElRFrf.js → createSvgIcon-DlIk-fDn.js} +3 -3
- package/admin/assets/hostInit-OBG53iVO.js +2 -0
- package/admin/assets/index-BCK6q-N6.css +1 -0
- package/admin/assets/{index-BLZa2V1g.js → index-BMwfsknM.js} +1 -1
- package/admin/assets/{index-Dr_ZFwru.css → index-BTsjunTt.css} +1 -1
- package/admin/assets/{index-CMttI-gM.js → index-BWM5lJbO.js} +4 -4
- package/admin/assets/index-Br_QjNUk.js +942 -0
- package/admin/assets/index-CePzv5-W.js +1294 -0
- package/admin/assets/index-Cjl4b70e.js +5 -0
- package/admin/assets/{index-BompUVvy.js → index-DZ3lKVw8.js} +1 -1
- package/admin/assets/{index-DmpUKunr.js → index-DwcZPzOL.js} +2 -2
- package/admin/assets/index-OIiv3PJA.js +16 -0
- package/admin/assets/{inheritsLoose-CLw44UEv.js → inheritsLoose-DNrhibGS.js} +1 -1
- package/admin/assets/{iobroker_javascript__loadShare__react__loadShare__-B-pIv4x_.js → iobroker_javascript__loadShare__react__loadShare__-i8pXne9X.js} +1 -1
- package/admin/assets/iobroker_javascript__mf_v__runtimeInit__mf_v__-DZdFIfoQ.js +5 -0
- package/admin/assets/preload-helper-BDBacUwf.js +1 -0
- package/admin/assets/useTheme-DakN8Abq.js +1 -0
- package/admin/custom/assets/{Components-za_0yG9W.js → Components-DjQ_LxKw.js} +1 -1
- package/admin/custom/assets/{ConfigCustomJavascriptSet__loadShare___mf_0_iobroker_mf_1_adapter_mf_2_react_mf_2_v5__loadShare__-BHJt30My.js → ConfigCustomJavascriptSet__loadShare___mf_0_iobroker_mf_1_adapter_mf_2_react_mf_2_v5__loadShare__-DaN0pfsw.js} +1 -1
- package/admin/custom/assets/{ConfigCustomJavascriptSet__loadShare___mf_0_mui_mf_1_material__loadShare__-WrqdT1Hz.js → ConfigCustomJavascriptSet__loadShare___mf_0_mui_mf_1_material__loadShare__-BqzgglHd.js} +1 -1
- package/admin/custom/assets/{ConfigCustomJavascriptSet__loadShare__react__loadShare__-B_YWmFeG.js → ConfigCustomJavascriptSet__loadShare__react__loadShare__-BNbscXK6.js} +1 -1
- package/admin/custom/assets/{ConfigCustomJavascriptSet__loadShare__react_mf_2_dom__loadShare__-DYzjQQsF.js → ConfigCustomJavascriptSet__loadShare__react_mf_2_dom__loadShare__-N2_tx_mJ.js} +1 -1
- package/admin/custom/assets/ConfigCustomJavascriptSet__mf_v__runtimeInit__mf_v__-jdUmHa_i.js +5 -0
- package/admin/custom/assets/DefaultPropsProvider-B8ZCC-c2.js +1 -0
- package/admin/custom/assets/DefaultPropsProvider-DfdXSIBu.js +1 -0
- package/admin/custom/assets/{FilledInput-BGGUNS4j.js → FilledInput-CSjr0QT8.js} +2 -2
- package/admin/custom/assets/{Tabs-DjdFNknI.js → Tabs-CiTQkBjL.js} +6 -6
- package/admin/custom/assets/{ThemeProvider-Uan4kCQd.js → ThemeProvider-C50pIiW4.js} +2 -2
- package/admin/custom/assets/_commonjsHelpers-CE1G-McA.js +1 -0
- package/admin/custom/assets/{createSvgIcon-BxCMHFh5.js → createSvgIcon-C7qUEvjp.js} +1 -1
- package/admin/custom/assets/createTheme-Bm92JF8u.js +8 -0
- package/admin/custom/assets/defaultTheme-BlO0eCf6.js +1 -0
- package/admin/custom/assets/{hostInit-CrAs5YZS.js → hostInit-BJ6gSofk.js} +2 -2
- package/admin/custom/assets/index-4wMOc304.js +1 -0
- package/admin/custom/assets/{index-UhQfKbTz.js → index-5CTGLw4h.js} +1 -1
- package/admin/custom/assets/index-BHN4DzE4.js +908 -0
- package/admin/custom/assets/{index-yiPj_-Rb.js → index-BkjEWGjf.js} +1 -1
- package/admin/custom/assets/{index-bxilEzdP.js → index-COcxCdeX.js} +2 -18
- package/admin/custom/assets/{index-DXg_kRe6.js → index-CnpybLRW.js} +1 -1
- package/admin/custom/assets/{index-ClFSKKDu.js → index-Db8nkuMR.js} +2 -2
- package/admin/custom/assets/{index-B2rBO0oC.js → index-DcK0RDrH.js} +1 -1
- package/admin/custom/assets/{index-7YkEnLQM.js → index-Df6OaCxx.js} +1 -1
- package/admin/custom/assets/{index-DOnIDI_a.js → index-Dx7rDE4p.js} +1 -1
- package/admin/custom/assets/index-t-NMdeH5.js +31 -0
- package/admin/custom/assets/index-u8R8UVCf.js +1393 -0
- package/admin/custom/assets/jsx-runtime-C1csJtRx.js +1 -0
- package/admin/custom/assets/leaflet-src-DpWQqQWv.js +1 -0
- package/admin/custom/assets/preload-helper-BDBacUwf.js +1 -0
- package/admin/custom/assets/useEnhancedEffect-aUb-5tTL.js +1 -0
- package/admin/custom/assets/{useTheme-DWmRkwMP.js → useTheme-Cgjfsi-1.js} +1 -1
- package/admin/custom/assets/useTheme-DFGylj2o.js +1 -0
- package/admin/custom/assets/virtualExposes-C_DtjFte.js +2 -0
- package/admin/custom/customComponents.js +2 -2
- package/admin/i18n/de.json +1 -1
- package/admin/mf-manifest.json +1 -1
- package/admin/remoteEntry.js +2 -2
- package/admin/tab.html +10 -13
- package/build/lib/crypto.js +32 -0
- package/build/lib/crypto.js.map +1 -0
- package/{build-backend → build}/lib/javascript.d.ts +3 -0
- package/{build-backend → build}/lib/utils.js.map +1 -1
- package/{build-backend → build}/main.js +20 -12
- package/build/main.js.map +1 -0
- package/{build-backend → build}/types.d.ts +1 -0
- package/docs/en/javascript.md +1 -1
- package/io-package.json +14 -14
- package/package.json +21 -20
- package/admin/assets/OpenAiDialog-BYXyaWDU.js +0 -36
- package/admin/assets/hostInit-fzxL8JAx.js +0 -2
- package/admin/assets/index-BUU5hWiL.js +0 -1294
- package/admin/assets/index-DUBaHZ92.css +0 -1
- package/admin/assets/index-DeFm7TiX.js +0 -5
- package/admin/assets/index-T5pCS60x.js +0 -16
- package/admin/assets/index-fhg5Z_KX.js +0 -930
- package/admin/assets/iobroker_javascript__mf_v__runtimeInit__mf_v__-CmuPLb0X.js +0 -5
- package/admin/assets/preload-helper-Dp1pzeXC.js +0 -1
- package/admin/assets/useTheme-CpAj0H76.js +0 -1
- package/admin/custom/assets/ConfigCustomJavascriptSet__mf_v__runtimeInit__mf_v__-Cib3-eWa.js +0 -5
- package/admin/custom/assets/DefaultPropsProvider-B41fRCEO.js +0 -1
- package/admin/custom/assets/DefaultPropsProvider-CfXkmG16.js +0 -7
- package/admin/custom/assets/_commonjsHelpers-D6-XlEtG.js +0 -1
- package/admin/custom/assets/createTheme-Ajie0adn.js +0 -16
- package/admin/custom/assets/defaultTheme-C_aSR-NR.js +0 -1
- package/admin/custom/assets/index-BkKMt4bp.js +0 -31
- package/admin/custom/assets/index-Bw5ZKbIF.js +0 -1399
- package/admin/custom/assets/index-Co3YA5NW.js +0 -9
- package/admin/custom/assets/index-DsPFm5o5.js +0 -904
- package/admin/custom/assets/jsx-runtime-lE4rOet2.js +0 -9
- package/admin/custom/assets/leaflet-src-A2ZHl6nF.js +0 -4
- package/admin/custom/assets/preload-helper-Dp1pzeXC.js +0 -1
- package/admin/custom/assets/useEnhancedEffect-DSK35Rma.js +0 -8
- package/admin/custom/assets/useTheme-CpiJlUE9.js +0 -1
- package/admin/custom/assets/virtualExposes-4pgHXHfp.js +0 -2
- package/build-backend/main.js.map +0 -1
- /package/{build-backend → build}/lib/consts.js +0 -0
- /package/{build-backend → build}/lib/consts.js.map +0 -0
- /package/{build-backend → build}/lib/convert.js +0 -0
- /package/{build-backend → build}/lib/convert.js.map +0 -0
- /package/{build-backend → build}/lib/debug.js +0 -0
- /package/{build-backend → build}/lib/debug.js.map +0 -0
- /package/{build-backend → build}/lib/debugger.js +0 -0
- /package/{build-backend → build}/lib/debugger.js.map +0 -0
- /package/{build-backend → build}/lib/eventObj.js +0 -0
- /package/{build-backend → build}/lib/eventObj.js.map +0 -0
- /package/{build-backend → build}/lib/inspect.js +0 -0
- /package/{build-backend → build}/lib/inspect.js.map +0 -0
- /package/{build-backend → build}/lib/mirror.js +0 -0
- /package/{build-backend → build}/lib/mirror.js.map +0 -0
- /package/{build-backend → build}/lib/nodeModulesManagement.js +0 -0
- /package/{build-backend → build}/lib/nodeModulesManagement.js.map +0 -0
- /package/{build-backend → build}/lib/patternCompareFunctions.js +0 -0
- /package/{build-backend → build}/lib/patternCompareFunctions.js.map +0 -0
- /package/{build-backend → build}/lib/protectFs.js +0 -0
- /package/{build-backend → build}/lib/protectFs.js.map +0 -0
- /package/{build-backend → build}/lib/request.js +0 -0
- /package/{build-backend → build}/lib/request.js.map +0 -0
- /package/{build-backend → build}/lib/sandbox.js +0 -0
- /package/{build-backend → build}/lib/sandbox.js.map +0 -0
- /package/{build-backend → build}/lib/scheduler.js +0 -0
- /package/{build-backend → build}/lib/scheduler.js.map +0 -0
- /package/{build-backend → build}/lib/tools.js +0 -0
- /package/{build-backend → build}/lib/tools.js.map +0 -0
- /package/{build-backend → build}/lib/typescriptSettings.js +0 -0
- /package/{build-backend → build}/lib/typescriptSettings.js.map +0 -0
- /package/{build-backend → build}/lib/typescriptTools.js +0 -0
- /package/{build-backend → build}/lib/typescriptTools.js.map +0 -0
- /package/{build-backend → build}/lib/utils.js +0 -0
- /package/{build-backend → build}/lib/words.js +0 -0
- /package/{build-backend → build}/lib/words.js.map +0 -0
package/README.md
CHANGED
|
@@ -26,6 +26,9 @@ Executes Javascript, Typescript Scripts.
|
|
|
26
26
|
<!--
|
|
27
27
|
### **WORK IN PROGRESS**
|
|
28
28
|
-->
|
|
29
|
+
### 9.0.13 (2025-12-05)
|
|
30
|
+
* (@GermanBluefox) Added possibility to encrypt scripts with password (only for vendors)
|
|
31
|
+
|
|
29
32
|
### 9.0.11 (2025-07-29)
|
|
30
33
|
* (@GermanBluefox) Corrected the rule editor if the condition is empty
|
|
31
34
|
* (@GermanBluefox) Corrected types for TypeScript
|
|
@@ -44,11 +47,6 @@ Executes Javascript, Typescript Scripts.
|
|
|
44
47
|
* (@GermanBluefox) Speed-up loading of GUI
|
|
45
48
|
* (@GermanBluefox) Migrating old blocks to new format
|
|
46
49
|
|
|
47
|
-
### 9.0.4 (2025-06-16)
|
|
48
|
-
* (@GermanBluefox) Corrected script editor for Polish language
|
|
49
|
-
* (@GermanBluefox) Corrected import of Blockly blocks
|
|
50
|
-
* (@GermanBluefox) Corrected editing of Blockly
|
|
51
|
-
|
|
52
50
|
## License
|
|
53
51
|
The MIT License (MIT)
|
|
54
52
|
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import{c as pr,j as P}from"./createSvgIcon-DlIk-fDn.js";import{i as Z}from"./iobroker_javascript__loadShare__react__loadShare__-i8pXne9X.js";import{i as j,c as pn,C as gr}from"./index-Cjl4b70e.js";import{i as U,h as _r}from"./index-CePzv5-W.js";import{_ as yr}from"./preload-helper-BDBacUwf.js";import{C as wr,t as br}from"./index-DZ3lKVw8.js";import xr from"./ScriptEditorVanillaMonaco-Xge2wqgO.js";import"./_commonjsHelpers-Cpj98o6Y.js";import"./iobroker_javascript__mf_v__runtimeInit__mf_v__-DZdFIfoQ.js";import"./inheritsLoose-DNrhibGS.js";const Sr=pr(P.jsx("path",{d:"M11.07 12.85c.77-1.39 2.25-2.21 3.11-3.44.91-1.29.4-3.7-2.18-3.7-1.69 0-2.52 1.28-2.87 2.34L6.54 6.96C7.25 4.83 9.18 3 11.99 3c2.35 0 3.96 1.07 4.78 2.41.7 1.15 1.11 3.3.03 4.9-1.2 1.77-2.35 2.31-2.97 3.45-.25.46-.35.76-.35 2.24h-2.89c-.01-.78-.13-2.05.48-3.15M14 20c0 1.1-.9 2-2 2s-2-.9-2-2 .9-2 2-2 2 .9 2 2"}),"QuestionMark");function R(s,e,t,n,r){if(typeof e=="function"?s!==e||!0:!e.has(s))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(s,t),t}function c(s,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?s!==e||!n:!e.has(s))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(s):n?n.value:e.get(s)}let qn=function(){const{crypto:s}=globalThis;if(s!=null&&s.randomUUID)return qn=s.randomUUID.bind(s),s.randomUUID();const e=new Uint8Array(1),t=s?()=>s.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^t()&15>>+n/4).toString(16))};function Et(s){return typeof s=="object"&&s!==null&&("name"in s&&s.name==="AbortError"||"message"in s&&String(s.message).includes("FetchRequestCanceledException"))}const Pt=s=>{if(s instanceof Error)return s;if(typeof s=="object"&&s!==null){try{if(Object.prototype.toString.call(s)==="[object Error]"){const e=new Error(s.message,s.cause?{cause:s.cause}:{});return s.stack&&(e.stack=s.stack),s.cause&&!e.cause&&(e.cause=s.cause),s.name&&(e.name=s.name),e}}catch{}try{return new Error(JSON.stringify(s))}catch{}}return new Error(s)};class x extends Error{}class H extends x{constructor(e,t,n,r){super(`${H.makeMessage(e,t,n)}`),this.status=e,this.headers=r,this.requestID=r==null?void 0:r.get("x-request-id"),this.error=t;const a=t;this.code=a==null?void 0:a.code,this.param=a==null?void 0:a.param,this.type=a==null?void 0:a.type}static makeMessage(e,t,n){const r=t!=null&&t.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&r?`${e} ${r}`:e?`${e} status code (no body)`:r||"(no status code or body)"}static generate(e,t,n,r){if(!e||!r)return new pt({message:n,cause:Pt(t)});const a=t==null?void 0:t.error;return e===400?new Jn(e,a,n,r):e===401?new Hn(e,a,n,r):e===403?new Xn(e,a,n,r):e===404?new Kn(e,a,n,r):e===409?new Vn(e,a,n,r):e===422?new Gn(e,a,n,r):e===429?new Qn(e,a,n,r):e>=500?new zn(e,a,n,r):new H(e,a,n,r)}}class z extends H{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class pt extends H{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}}class Jt extends pt{constructor({message:e}={}){super({message:e??"Request timed out."})}}class Jn extends H{}class Hn extends H{}class Xn extends H{}class Kn extends H{}class Vn extends H{}class Gn extends H{}class Qn extends H{}class zn extends H{}class Yn extends x{constructor(){super("Could not parse response content as the length limit was reached")}}class Zn extends x{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class Re extends Error{constructor(e){super(e)}}const Ar=/^[a-z][a-z0-9+.-]*:/i,vr=s=>Ar.test(s);let K=s=>(K=Array.isArray,K(s)),gn=K;function es(s){return typeof s!="object"?{}:s??{}}function Cr(s){if(!s)return!0;for(const e in s)return!1;return!0}function Ir(s,e){return Object.prototype.hasOwnProperty.call(s,e)}function St(s){return s!=null&&typeof s=="object"&&!Array.isArray(s)}const Rr=(s,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new x(`${s} must be an integer`);if(e<0)throw new x(`${s} must be a positive integer`);return e},$r=s=>{try{return JSON.parse(s)}catch{return}},Be=s=>new Promise(e=>setTimeout(e,s)),we="5.23.2",kr=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function Or(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}const Er=()=>{var t;const s=Or();if(s==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":we,"X-Stainless-OS":yn(Deno.build.os),"X-Stainless-Arch":_n(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:((t=Deno.version)==null?void 0:t.deno)??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":we,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(s==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":we,"X-Stainless-OS":yn(globalThis.process.platform??"unknown"),"X-Stainless-Arch":_n(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const e=Pr();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":we,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":we,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Pr(){if(typeof navigator>"u"||!navigator)return null;const s=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(const{key:e,pattern:t}of s){const n=t.exec(navigator.userAgent);if(n){const r=n[1]||0,a=n[2]||0,i=n[3]||0;return{browser:e,version:`${r}.${a}.${i}`}}}return null}const _n=s=>s==="x32"?"x32":s==="x86_64"||s==="x64"?"x64":s==="arm"?"arm":s==="aarch64"||s==="arm64"?"arm64":s?`other:${s}`:"unknown",yn=s=>(s=s.toLowerCase(),s.includes("ios")?"iOS":s==="android"?"Android":s==="darwin"?"MacOS":s==="win32"?"Windows":s==="freebsd"?"FreeBSD":s==="openbsd"?"OpenBSD":s==="linux"?"Linux":s?`Other:${s}`:"Unknown");let wn;const Tr=()=>wn??(wn=Er());function Mr(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function ts(...s){const e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...s)}function ns(s){let e=Symbol.asyncIterator in s?s[Symbol.asyncIterator]():s[Symbol.iterator]();return ts({start(){},async pull(t){const{done:n,value:r}=await e.next();n?t.close():t.enqueue(r)},async cancel(){var t;await((t=e.return)==null?void 0:t.call(e))}})}function ss(s){if(s[Symbol.asyncIterator])return s;const e=s.getReader();return{async next(){try{const t=await e.read();return t!=null&&t.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){const t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function Nr(s){var n,r;if(s===null||typeof s!="object")return;if(s[Symbol.asyncIterator]){await((r=(n=s[Symbol.asyncIterator]()).return)==null?void 0:r.call(n));return}const e=s.getReader(),t=e.cancel();e.releaseLock(),await t}const jr=({headers:s,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)}),rs="RFC3986",as=s=>String(s),bn={RFC1738:s=>String(s).replace(/%20/g,"+"),RFC3986:as},Fr="RFC1738";let Tt=(s,e)=>(Tt=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Tt(s,e));const ee=(()=>{const s=[];for(let e=0;e<256;++e)s.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return s})(),At=1024,Lr=(s,e,t,n,r)=>{if(s.length===0)return s;let a=s;if(typeof s=="symbol"?a=Symbol.prototype.toString.call(s):typeof s!="string"&&(a=String(s)),t==="iso-8859-1")return escape(a).replace(/%u[0-9a-f]{4}/gi,function(o){return"%26%23"+parseInt(o.slice(2),16)+"%3B"});let i="";for(let o=0;o<a.length;o+=At){const l=a.length>=At?a.slice(o,o+At):a,u=[];for(let m=0;m<l.length;++m){let h=l.charCodeAt(m);if(h===45||h===46||h===95||h===126||h>=48&&h<=57||h>=65&&h<=90||h>=97&&h<=122||r===Fr&&(h===40||h===41)){u[u.length]=l.charAt(m);continue}if(h<128){u[u.length]=ee[h];continue}if(h<2048){u[u.length]=ee[192|h>>6]+ee[128|h&63];continue}if(h<55296||h>=57344){u[u.length]=ee[224|h>>12]+ee[128|h>>6&63]+ee[128|h&63];continue}m+=1,h=65536+((h&1023)<<10|l.charCodeAt(m)&1023),u[u.length]=ee[240|h>>18]+ee[128|h>>12&63]+ee[128|h>>6&63]+ee[128|h&63]}i+=u.join("")}return i};function Dr(s){return!s||typeof s!="object"?!1:!!(s.constructor&&s.constructor.isBuffer&&s.constructor.isBuffer(s))}function xn(s,e){if(K(s)){const t=[];for(let n=0;n<s.length;n+=1)t.push(e(s[n]));return t}return e(s)}const is={brackets(s){return String(s)+"[]"},comma:"comma",indices(s,e){return String(s)+"["+e+"]"},repeat(s){return String(s)}},os=function(s,e){Array.prototype.push.apply(s,K(e)?e:[e])};let Sn;const B={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Lr,encodeValuesOnly:!1,format:rs,formatter:as,indices:!1,serializeDate(s){return(Sn??(Sn=Function.prototype.call.bind(Date.prototype.toISOString)))(s)},skipNulls:!1,strictNullHandling:!1};function Br(s){return typeof s=="string"||typeof s=="number"||typeof s=="boolean"||typeof s=="symbol"||typeof s=="bigint"}const vt={};function cs(s,e,t,n,r,a,i,o,l,u,m,h,g,d,b,w,v,E){let p=s,y=E,_=0,C=!1;for(;(y=y.get(vt))!==void 0&&!C;){const T=y.get(s);if(_+=1,typeof T<"u"){if(T===_)throw new RangeError("Cyclic object value");C=!0}typeof y.get(vt)>"u"&&(_=0)}if(typeof u=="function"?p=u(e,p):p instanceof Date?p=g==null?void 0:g(p):t==="comma"&&K(p)&&(p=xn(p,function(T){return T instanceof Date?g==null?void 0:g(T):T})),p===null){if(a)return l&&!w?l(e,B.encoder,v,"key",d):e;p=""}if(Br(p)||Dr(p)){if(l){const T=w?e:l(e,B.encoder,v,"key",d);return[(b==null?void 0:b(T))+"="+(b==null?void 0:b(l(p,B.encoder,v,"value",d)))]}return[(b==null?void 0:b(e))+"="+(b==null?void 0:b(String(p)))]}const k=[];if(typeof p>"u")return k;let $;if(t==="comma"&&K(p))w&&l&&(p=xn(p,l)),$=[{value:p.length>0?p.join(",")||null:void 0}];else if(K(u))$=u;else{const T=Object.keys(p);$=m?T.sort(m):T}const F=o?String(e).replace(/\./g,"%2E"):String(e),A=n&&K(p)&&p.length===1?F+"[]":F;if(r&&K(p)&&p.length===0)return A+"[]";for(let T=0;T<$.length;++T){const M=$[T],se=typeof M=="object"&&typeof M.value<"u"?M.value:p[M];if(i&&se===null)continue;const me=h&&o?M.replace(/\./g,"%2E"):M,N=K(p)?typeof t=="function"?t(A,me):A:A+(h?"."+me:"["+me+"]");E.set(s,_);const ie=new WeakMap;ie.set(vt,E),os(k,cs(se,N,t,n,r,a,i,o,t==="comma"&&w&&K(p)?null:l,u,m,h,g,d,b,w,v,ie))}return k}function Wr(s=B){if(typeof s.allowEmptyArrays<"u"&&typeof s.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof s.encodeDotInKeys<"u"&&typeof s.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(s.encoder!==null&&typeof s.encoder<"u"&&typeof s.encoder!="function")throw new TypeError("Encoder has to be a function.");const e=s.charset||B.charset;if(typeof s.charset<"u"&&s.charset!=="utf-8"&&s.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let t=rs;if(typeof s.format<"u"){if(!Tt(bn,s.format))throw new TypeError("Unknown format option provided.");t=s.format}const n=bn[t];let r=B.filter;(typeof s.filter=="function"||K(s.filter))&&(r=s.filter);let a;if(s.arrayFormat&&s.arrayFormat in is?a=s.arrayFormat:"indices"in s?a=s.indices?"indices":"repeat":a=B.arrayFormat,"commaRoundTrip"in s&&typeof s.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");const i=typeof s.allowDots>"u"?s.encodeDotInKeys?!0:B.allowDots:!!s.allowDots;return{addQueryPrefix:typeof s.addQueryPrefix=="boolean"?s.addQueryPrefix:B.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof s.allowEmptyArrays=="boolean"?!!s.allowEmptyArrays:B.allowEmptyArrays,arrayFormat:a,charset:e,charsetSentinel:typeof s.charsetSentinel=="boolean"?s.charsetSentinel:B.charsetSentinel,commaRoundTrip:!!s.commaRoundTrip,delimiter:typeof s.delimiter>"u"?B.delimiter:s.delimiter,encode:typeof s.encode=="boolean"?s.encode:B.encode,encodeDotInKeys:typeof s.encodeDotInKeys=="boolean"?s.encodeDotInKeys:B.encodeDotInKeys,encoder:typeof s.encoder=="function"?s.encoder:B.encoder,encodeValuesOnly:typeof s.encodeValuesOnly=="boolean"?s.encodeValuesOnly:B.encodeValuesOnly,filter:r,format:t,formatter:n,serializeDate:typeof s.serializeDate=="function"?s.serializeDate:B.serializeDate,skipNulls:typeof s.skipNulls=="boolean"?s.skipNulls:B.skipNulls,sort:typeof s.sort=="function"?s.sort:null,strictNullHandling:typeof s.strictNullHandling=="boolean"?s.strictNullHandling:B.strictNullHandling}}function Ur(s,e={}){let t=s;const n=Wr(e);let r,a;typeof n.filter=="function"?(a=n.filter,t=a("",t)):K(n.filter)&&(a=n.filter,r=a);const i=[];if(typeof t!="object"||t===null)return"";const o=is[n.arrayFormat],l=o==="comma"&&n.commaRoundTrip;r||(r=Object.keys(t)),n.sort&&r.sort(n.sort);const u=new WeakMap;for(let g=0;g<r.length;++g){const d=r[g];n.skipNulls&&t[d]===null||os(i,cs(t[d],d,o,l,n.allowEmptyArrays,n.strictNullHandling,n.skipNulls,n.encodeDotInKeys,n.encode?n.encoder:null,n.filter,n.sort,n.allowDots,n.serializeDate,n.format,n.formatter,n.encodeValuesOnly,n.charset,u))}const m=i.join(n.delimiter);let h=n.addQueryPrefix===!0?"?":"";return n.charsetSentinel&&(n.charset==="iso-8859-1"?h+="utf8=%26%2310003%3B&":h+="utf8=%E2%9C%93&"),m.length>0?h+m:""}function qr(s){let e=0;for(const r of s)e+=r.length;const t=new Uint8Array(e);let n=0;for(const r of s)t.set(r,n),n+=r.length;return t}let An;function Ht(s){let e;return(An??(e=new globalThis.TextEncoder,An=e.encode.bind(e)))(s)}let vn;function Cn(s){let e;return(vn??(e=new globalThis.TextDecoder,vn=e.decode.bind(e)))(s)}var V,G;class gt{constructor(){V.set(this,void 0),G.set(this,void 0),R(this,V,new Uint8Array),R(this,G,null)}decode(e){if(e==null)return[];const t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?Ht(e):e;R(this,V,qr([c(this,V,"f"),t]));const n=[];let r;for(;(r=Jr(c(this,V,"f"),c(this,G,"f")))!=null;){if(r.carriage&&c(this,G,"f")==null){R(this,G,r.index);continue}if(c(this,G,"f")!=null&&(r.index!==c(this,G,"f")+1||r.carriage)){n.push(Cn(c(this,V,"f").subarray(0,c(this,G,"f")-1))),R(this,V,c(this,V,"f").subarray(c(this,G,"f"))),R(this,G,null);continue}const a=c(this,G,"f")!==null?r.preceding-1:r.preceding,i=Cn(c(this,V,"f").subarray(0,a));n.push(i),R(this,V,c(this,V,"f").subarray(r.index)),R(this,G,null)}return n}flush(){return c(this,V,"f").length?this.decode(`
|
|
2
|
+
`):[]}}V=new WeakMap,G=new WeakMap;gt.NEWLINE_CHARS=new Set([`
|
|
3
|
+
`,"\r"]);gt.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Jr(s,e){for(let r=e??0;r<s.length;r++){if(s[r]===10)return{preceding:r,index:r+1,carriage:!1};if(s[r]===13)return{preceding:r,index:r+1,carriage:!0}}return null}function Hr(s){for(let n=0;n<s.length-1;n++){if(s[n]===10&&s[n+1]===10||s[n]===13&&s[n+1]===13)return n+2;if(s[n]===13&&s[n+1]===10&&n+3<s.length&&s[n+2]===13&&s[n+3]===10)return n+4}return-1}const ot={off:0,error:200,warn:300,info:400,debug:500},In=(s,e,t)=>{if(s){if(Ir(ot,s))return s;q(t).warn(`${e} was set to ${JSON.stringify(s)}, expected one of ${JSON.stringify(Object.keys(ot))}`)}};function $e(){}function Je(s,e,t){return!e||ot[s]>ot[t]?$e:e[s].bind(e)}const Xr={error:$e,warn:$e,info:$e,debug:$e};let Rn=new WeakMap;function q(s){const e=s.logger,t=s.logLevel??"off";if(!e)return Xr;const n=Rn.get(e);if(n&&n[0]===t)return n[1];const r={error:Je("error",e,t),warn:Je("warn",e,t),info:Je("info",e,t),debug:Je("debug",e,t)};return Rn.set(e,[t,r]),r}const le=s=>(s.options&&(s.options={...s.options},delete s.options.headers),s.headers&&(s.headers=Object.fromEntries((s.headers instanceof Headers?[...s.headers]:Object.entries(s.headers)).map(([e,t])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":t]))),"retryOfRequestLogID"in s&&(s.retryOfRequestLogID&&(s.retryOf=s.retryOfRequestLogID),delete s.retryOfRequestLogID),s);var Ie;class ne{constructor(e,t,n){this.iterator=e,Ie.set(this,void 0),this.controller=t,R(this,Ie,n)}static fromSSEResponse(e,t,n){let r=!1;const a=n?q(n):console;async function*i(){if(r)throw new x("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let o=!1;try{for await(const l of Kr(e,t))if(!o){if(l.data.startsWith("[DONE]")){o=!0;continue}if(l.event===null||!l.event.startsWith("thread.")){let u;try{u=JSON.parse(l.data)}catch(m){throw a.error("Could not parse message into JSON:",l.data),a.error("From chunk:",l.raw),m}if(u&&u.error)throw new H(void 0,u.error,void 0,e.headers);yield u}else{let u;try{u=JSON.parse(l.data)}catch(m){throw console.error("Could not parse message into JSON:",l.data),console.error("From chunk:",l.raw),m}if(l.event=="error")throw new H(void 0,u.error,u.message,void 0);yield{event:l.event,data:u}}}o=!0}catch(l){if(Et(l))return;throw l}finally{o||t.abort()}}return new ne(i,t,n)}static fromReadableStream(e,t,n){let r=!1;async function*a(){const o=new gt,l=ss(e);for await(const u of l)for(const m of o.decode(u))yield m;for(const u of o.flush())yield u}async function*i(){if(r)throw new x("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let o=!1;try{for await(const l of a())o||l&&(yield JSON.parse(l));o=!0}catch(l){if(Et(l))return;throw l}finally{o||t.abort()}}return new ne(i,t,n)}[(Ie=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){const e=[],t=[],n=this.iterator(),r=a=>({next:()=>{if(a.length===0){const i=n.next();e.push(i),t.push(i)}return a.shift()}});return[new ne(()=>r(e),this.controller,c(this,Ie,"f")),new ne(()=>r(t),this.controller,c(this,Ie,"f"))]}toReadableStream(){const e=this;let t;return ts({async start(){t=e[Symbol.asyncIterator]()},async pull(n){try{const{value:r,done:a}=await t.next();if(a)return n.close();const i=Ht(JSON.stringify(r)+`
|
|
4
|
+
`);n.enqueue(i)}catch(r){n.error(r)}},async cancel(){var n;await((n=t.return)==null?void 0:n.call(t))}})}}async function*Kr(s,e){if(!s.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new x("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new x("Attempted to iterate over a response with no body");const t=new Gr,n=new gt,r=ss(s.body);for await(const a of Vr(r))for(const i of n.decode(a)){const o=t.decode(i);o&&(yield o)}for(const a of n.flush()){const i=t.decode(a);i&&(yield i)}}async function*Vr(s){let e=new Uint8Array;for await(const t of s){if(t==null)continue;const n=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?Ht(t):t;let r=new Uint8Array(e.length+n.length);r.set(e),r.set(n,e.length),e=r;let a;for(;(a=Hr(e))!==-1;)yield e.slice(0,a),e=e.slice(a)}e.length>0&&(yield e)}class Gr{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;const a={event:this.event,data:this.data.join(`
|
|
5
|
+
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],a}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,n,r]=Qr(e,":");return r.startsWith(" ")&&(r=r.substring(1)),t==="event"?this.event=r:t==="data"&&this.data.push(r),null}}function Qr(s,e){const t=s.indexOf(e);return t!==-1?[s.substring(0,t),e,s.substring(t+e.length)]:[s,"",""]}async function ls(s,e){const{response:t,requestLogID:n,retryOfRequestLogID:r,startTime:a}=e,i=await(async()=>{var h;if(e.options.stream)return q(s).debug("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller,s):ne.fromSSEResponse(t,e.controller,s);if(t.status===204)return null;if(e.options.__binaryResponse)return t;const o=t.headers.get("content-type"),l=(h=o==null?void 0:o.split(";")[0])==null?void 0:h.trim();if((l==null?void 0:l.includes("application/json"))||(l==null?void 0:l.endsWith("+json"))){const g=await t.json();return us(g,t)}return await t.text()})();return q(s).debug(`[${n}] response parsed`,le({retryOfRequestLogID:r,url:t.url,status:t.status,body:i,durationMs:Date.now()-a})),i}function us(s,e){return!s||typeof s!="object"||Array.isArray(s)?s:Object.defineProperty(s,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}var ke;class _t extends Promise{constructor(e,t,n=ls){super(r=>{r(null)}),this.responsePromise=t,this.parseResponse=n,ke.set(this,void 0),R(this,ke,e)}_thenUnwrap(e){return new _t(c(this,ke,"f"),this.responsePromise,async(t,n)=>us(e(await this.parseResponse(t,n),n),n.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){const[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(c(this,ke,"f"),e))),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}}ke=new WeakMap;var He;class Xt{constructor(e,t,n,r){He.set(this,void 0),R(this,He,e),this.options=r,this.response=t,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){const e=this.nextPageRequestOptions();if(!e)throw new x("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await c(this,He,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(He=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}}class zr extends _t{constructor(e,t,n){super(e,t,async(r,a)=>new n(r,a.response,await ls(r,a),a.options))}async*[Symbol.asyncIterator](){const e=await this;for await(const t of e)yield t}}class yt extends Xt{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.object=n.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}}class L extends Xt{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.has_more=n.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){var n;const e=this.getPaginatedItems(),t=(n=e[e.length-1])==null?void 0:n.id;return t?{...this.options,query:{...es(this.options.query),after:t}}:null}}class Yr extends Xt{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.has_more=n.has_more||!1,this.last_id=n.last_id||""}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){const e=this.last_id;return e?{...this.options,query:{...es(this.options.query),after:e}}:null}}const hs=()=>{var s;if(typeof File>"u"){const{process:e}=globalThis,t=typeof((s=e==null?void 0:e.versions)==null?void 0:s.node)=="string"&&parseInt(e.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(t?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function je(s,e,t){return hs(),new File(s,e??"unknown_file",t)}function Ye(s){return(typeof s=="object"&&s!==null&&("name"in s&&s.name&&String(s.name)||"url"in s&&s.url&&String(s.url)||"filename"in s&&s.filename&&String(s.filename)||"path"in s&&s.path&&String(s.path))||"").split(/[\\/]/).pop()||void 0}const ds=s=>s!=null&&typeof s=="object"&&typeof s[Symbol.asyncIterator]=="function",fe=async(s,e)=>({...s,body:await ea(s.body,e)}),$n=new WeakMap;function Zr(s){const e=typeof s=="function"?s:s.fetch,t=$n.get(e);if(t)return t;const n=(async()=>{try{const r="Response"in e?e.Response:(await e("data:,")).constructor,a=new FormData;return a.toString()!==await new r(a).text()}catch{return!0}})();return $n.set(e,n),n}const ea=async(s,e)=>{if(!await Zr(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");const t=new FormData;return await Promise.all(Object.entries(s||{}).map(([n,r])=>Mt(t,n,r))),t},ta=s=>s instanceof Blob&&"name"in s,Mt=async(s,e,t)=>{if(t!==void 0){if(t==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")s.append(e,String(t));else if(t instanceof Response)s.append(e,je([await t.blob()],Ye(t)));else if(ds(t))s.append(e,je([await new Response(ns(t)).blob()],Ye(t)));else if(ta(t))s.append(e,t,Ye(t));else if(Array.isArray(t))await Promise.all(t.map(n=>Mt(s,e+"[]",n)));else if(typeof t=="object")await Promise.all(Object.entries(t).map(([n,r])=>Mt(s,`${e}[${n}]`,r)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${t} instead`)}},fs=s=>s!=null&&typeof s=="object"&&typeof s.size=="number"&&typeof s.type=="string"&&typeof s.text=="function"&&typeof s.slice=="function"&&typeof s.arrayBuffer=="function",na=s=>s!=null&&typeof s=="object"&&typeof s.name=="string"&&typeof s.lastModified=="number"&&fs(s),sa=s=>s!=null&&typeof s=="object"&&typeof s.url=="string"&&typeof s.blob=="function";async function ra(s,e,t){if(hs(),s=await s,na(s))return s instanceof File?s:je([await s.arrayBuffer()],s.name);if(sa(s)){const r=await s.blob();return e||(e=new URL(s.url).pathname.split(/[\\/]/).pop()),je(await Nt(r),e,t)}const n=await Nt(s);if(e||(e=Ye(s)),!(t!=null&&t.type)){const r=n.find(a=>typeof a=="object"&&"type"in a&&a.type);typeof r=="string"&&(t={...t,type:r})}return je(n,e,t)}async function Nt(s){var t;let e=[];if(typeof s=="string"||ArrayBuffer.isView(s)||s instanceof ArrayBuffer)e.push(s);else if(fs(s))e.push(s instanceof Blob?s:await s.arrayBuffer());else if(ds(s))for await(const n of s)e.push(...await Nt(n));else{const n=(t=s==null?void 0:s.constructor)==null?void 0:t.name;throw new Error(`Unexpected data type: ${typeof s}${n?`; constructor: ${n}`:""}${aa(s)}`)}return e}function aa(s){return typeof s!="object"||s===null?"":`; props: [${Object.getOwnPropertyNames(s).map(t=>`"${t}"`).join(", ")}]`}class I{constructor(e){this._client=e}}function ms(s){return s.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const kn=Object.freeze(Object.create(null)),ia=(s=ms)=>function(t,...n){if(t.length===1)return t[0];let r=!1;const a=[],i=t.reduce((m,h,g)=>{var w;/[?#]/.test(h)&&(r=!0);const d=n[g];let b=(r?encodeURIComponent:s)(""+d);return g!==n.length&&(d==null||typeof d=="object"&&d.toString===((w=Object.getPrototypeOf(Object.getPrototypeOf(d.hasOwnProperty??kn)??kn))==null?void 0:w.toString))&&(b=d+"",a.push({start:m.length+h.length,length:b.length,error:`Value of type ${Object.prototype.toString.call(d).slice(8,-1)} is not a valid path parameter`})),m+h+(g===n.length?"":b)},""),o=i.split(/[?#]/,1)[0],l=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi;let u;for(;(u=l.exec(o))!==null;)a.push({start:u.index,length:u[0].length,error:`Value "${u[0]}" can't be safely passed as a path parameter`});if(a.sort((m,h)=>m.start-h.start),a.length>0){let m=0;const h=a.reduce((g,d)=>{const b=" ".repeat(d.start-m),w="^".repeat(d.length);return m=d.start+d.length,g+b+w},"");throw new x(`Path parameters result in path with invalid segments:
|
|
6
|
+
${a.map(g=>g.error).join(`
|
|
7
|
+
`)}
|
|
8
|
+
${i}
|
|
9
|
+
${h}`)}return i},f=ia(ms);let ps=class extends I{list(e,t={},n){return this._client.getAPIList(f`/chat/completions/${e}/messages`,L,{query:t,...n})}};function ct(s){return s!==void 0&&"function"in s&&s.function!==void 0}function Kt(s){return(s==null?void 0:s.$brand)==="auto-parseable-response-format"}function We(s){return(s==null?void 0:s.$brand)==="auto-parseable-tool"}function oa(s,e){return!e||!gs(e)?{...s,choices:s.choices.map(t=>(_s(t.message.tool_calls),{...t,message:{...t.message,parsed:null,...t.message.tool_calls?{tool_calls:t.message.tool_calls}:void 0}}))}:Vt(s,e)}function Vt(s,e){const t=s.choices.map(n=>{var r;if(n.finish_reason==="length")throw new Yn;if(n.finish_reason==="content_filter")throw new Zn;return _s(n.message.tool_calls),{...n,message:{...n.message,...n.message.tool_calls?{tool_calls:((r=n.message.tool_calls)==null?void 0:r.map(a=>la(e,a)))??void 0}:void 0,parsed:n.message.content&&!n.message.refusal?ca(e,n.message.content):null}}});return{...s,choices:t}}function ca(s,e){var t,n;return((t=s.response_format)==null?void 0:t.type)!=="json_schema"?null:((n=s.response_format)==null?void 0:n.type)==="json_schema"?"$parseRaw"in s.response_format?s.response_format.$parseRaw(e):JSON.parse(e):null}function la(s,e){var n;const t=(n=s.tools)==null?void 0:n.find(r=>{var a;return ct(r)&&((a=r.function)==null?void 0:a.name)===e.function.name});return{...e,function:{...e.function,parsed_arguments:We(t)?t.$parseRaw(e.function.arguments):t!=null&&t.function.strict?JSON.parse(e.function.arguments):null}}}function ua(s,e){var n;if(!s||!("tools"in s)||!s.tools)return!1;const t=(n=s.tools)==null?void 0:n.find(r=>{var a;return ct(r)&&((a=r.function)==null?void 0:a.name)===e.function.name});return ct(t)&&(We(t)||(t==null?void 0:t.function.strict)||!1)}function gs(s){var e;return Kt(s.response_format)?!0:((e=s.tools)==null?void 0:e.some(t=>We(t)||t.type==="function"&&t.function.strict===!0))??!1}function _s(s){for(const e of s||[])if(e.type!=="function")throw new x(`Currently only \`function\` tool calls are supported; Received \`${e.type}\``)}function ha(s){for(const e of s??[]){if(e.type!=="function")throw new x(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new x(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}const lt=s=>(s==null?void 0:s.role)==="assistant",ys=s=>(s==null?void 0:s.role)==="tool";var jt,Ze,et,Oe,Ee,tt,Pe,ae,Te,ut,ht,be,ws;class Gt{constructor(){jt.add(this),this.controller=new AbortController,Ze.set(this,void 0),et.set(this,()=>{}),Oe.set(this,()=>{}),Ee.set(this,void 0),tt.set(this,()=>{}),Pe.set(this,()=>{}),ae.set(this,{}),Te.set(this,!1),ut.set(this,!1),ht.set(this,!1),be.set(this,!1),R(this,Ze,new Promise((e,t)=>{R(this,et,e,"f"),R(this,Oe,t,"f")})),R(this,Ee,new Promise((e,t)=>{R(this,tt,e,"f"),R(this,Pe,t,"f")})),c(this,Ze,"f").catch(()=>{}),c(this,Ee,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},c(this,jt,"m",ws).bind(this))},0)}_connected(){this.ended||(c(this,et,"f").call(this),this._emit("connect"))}get ended(){return c(this,Te,"f")}get errored(){return c(this,ut,"f")}get aborted(){return c(this,ht,"f")}abort(){this.controller.abort()}on(e,t){return(c(this,ae,"f")[e]||(c(this,ae,"f")[e]=[])).push({listener:t}),this}off(e,t){const n=c(this,ae,"f")[e];if(!n)return this;const r=n.findIndex(a=>a.listener===t);return r>=0&&n.splice(r,1),this}once(e,t){return(c(this,ae,"f")[e]||(c(this,ae,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{R(this,be,!0),e!=="error"&&this.once("error",n),this.once(e,t)})}async done(){R(this,be,!0),await c(this,Ee,"f")}_emit(e,...t){if(c(this,Te,"f"))return;e==="end"&&(R(this,Te,!0),c(this,tt,"f").call(this));const n=c(this,ae,"f")[e];if(n&&(c(this,ae,"f")[e]=n.filter(r=>!r.once),n.forEach(({listener:r})=>r(...t))),e==="abort"){const r=t[0];!c(this,be,"f")&&!(n!=null&&n.length)&&Promise.reject(r),c(this,Oe,"f").call(this,r),c(this,Pe,"f").call(this,r),this._emit("end");return}if(e==="error"){const r=t[0];!c(this,be,"f")&&!(n!=null&&n.length)&&Promise.reject(r),c(this,Oe,"f").call(this,r),c(this,Pe,"f").call(this,r),this._emit("end")}}_emitFinal(){}}Ze=new WeakMap,et=new WeakMap,Oe=new WeakMap,Ee=new WeakMap,tt=new WeakMap,Pe=new WeakMap,ae=new WeakMap,Te=new WeakMap,ut=new WeakMap,ht=new WeakMap,be=new WeakMap,jt=new WeakSet,ws=function(e){if(R(this,ut,!0),e instanceof Error&&e.name==="AbortError"&&(e=new z),e instanceof z)return R(this,ht,!0),this._emit("abort",e);if(e instanceof x)return this._emit("error",e);if(e instanceof Error){const t=new x(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new x(String(e)))};function da(s){return typeof s.parse=="function"}var X,Ft,dt,Lt,Dt,Bt,bs,xs;const fa=10;class Ss extends Gt{constructor(){super(...arguments),X.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){var n;this._chatCompletions.push(e),this._emit("chatCompletion",e);const t=(n=e.choices[0])==null?void 0:n.message;return t&&this._addMessage(t),e}_addMessage(e,t=!0){if("content"in e||(e.content=null),this.messages.push(e),t){if(this._emit("message",e),ys(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(lt(e)&&e.tool_calls)for(const n of e.tool_calls)n.type==="function"&&this._emit("functionToolCall",n.function)}}async finalChatCompletion(){await this.done();const e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new x("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),c(this,X,"m",Ft).call(this)}async finalMessage(){return await this.done(),c(this,X,"m",dt).call(this)}async finalFunctionToolCall(){return await this.done(),c(this,X,"m",Lt).call(this)}async finalFunctionToolCallResult(){return await this.done(),c(this,X,"m",Dt).call(this)}async totalUsage(){return await this.done(),c(this,X,"m",Bt).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){const e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);const t=c(this,X,"m",dt).call(this);t&&this._emit("finalMessage",t);const n=c(this,X,"m",Ft).call(this);n&&this._emit("finalContent",n);const r=c(this,X,"m",Lt).call(this);r&&this._emit("finalFunctionToolCall",r);const a=c(this,X,"m",Dt).call(this);a!=null&&this._emit("finalFunctionToolCallResult",a),this._chatCompletions.some(i=>i.usage)&&this._emit("totalUsage",c(this,X,"m",Bt).call(this))}async _createChatCompletion(e,t,n){const r=n==null?void 0:n.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),c(this,X,"m",bs).call(this,t);const a=await e.chat.completions.create({...t,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(Vt(a,t))}async _runChatCompletion(e,t,n){for(const r of t.messages)this._addMessage(r,!1);return await this._createChatCompletion(e,t,n)}async _runTools(e,t,n){var d,b,w;const r="tool",{tool_choice:a="auto",stream:i,...o}=t,l=typeof a!="string"&&a.type==="function"&&((d=a==null?void 0:a.function)==null?void 0:d.name),{maxChatCompletions:u=fa}=n||{},m=t.tools.map(v=>{if(We(v)){if(!v.$callback)throw new x("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:v.$callback,name:v.function.name,description:v.function.description||"",parameters:v.function.parameters,parse:v.$parseRaw,strict:!0}}}return v}),h={};for(const v of m)v.type==="function"&&(h[v.function.name||v.function.function.name]=v.function);const g="tools"in t?m.map(v=>v.type==="function"?{type:"function",function:{name:v.function.name||v.function.function.name,parameters:v.function.parameters,description:v.function.description,strict:v.function.strict}}:v):void 0;for(const v of t.messages)this._addMessage(v,!1);for(let v=0;v<u;++v){const p=(b=(await this._createChatCompletion(e,{...o,tool_choice:a,tools:g,messages:[...this.messages]},n)).choices[0])==null?void 0:b.message;if(!p)throw new x("missing message in ChatCompletion response");if(!((w=p.tool_calls)!=null&&w.length))return;for(const y of p.tool_calls){if(y.type!=="function")continue;const _=y.id,{name:C,arguments:k}=y.function,$=h[C];if($){if(l&&l!==C){const M=`Invalid tool_call: ${JSON.stringify(C)}. ${JSON.stringify(l)} requested. Please try again`;this._addMessage({role:r,tool_call_id:_,content:M});continue}}else{const M=`Invalid tool_call: ${JSON.stringify(C)}. Available options are: ${Object.keys(h).map(se=>JSON.stringify(se)).join(", ")}. Please try again`;this._addMessage({role:r,tool_call_id:_,content:M});continue}let F;try{F=da($)?await $.parse(k):k}catch(M){const se=M instanceof Error?M.message:String(M);this._addMessage({role:r,tool_call_id:_,content:se});continue}const A=await $.function(F,this),T=c(this,X,"m",xs).call(this,A);if(this._addMessage({role:r,tool_call_id:_,content:T}),l)return}}}}X=new WeakSet,Ft=function(){return c(this,X,"m",dt).call(this).content??null},dt=function(){let e=this.messages.length;for(;e-- >0;){const t=this.messages[e];if(lt(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new x("stream ended without producing a ChatCompletionMessage with role=assistant")},Lt=function(){var e,t;for(let n=this.messages.length-1;n>=0;n--){const r=this.messages[n];if(lt(r)&&((e=r==null?void 0:r.tool_calls)!=null&&e.length))return(t=r.tool_calls.filter(a=>a.type==="function").at(-1))==null?void 0:t.function}},Dt=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(ys(t)&&t.content!=null&&typeof t.content=="string"&&this.messages.some(n=>{var r;return n.role==="assistant"&&((r=n.tool_calls)==null?void 0:r.some(a=>a.type==="function"&&a.id===t.tool_call_id))}))return t.content}},Bt=function(){const e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(const{usage:t}of this._chatCompletions)t&&(e.completion_tokens+=t.completion_tokens,e.prompt_tokens+=t.prompt_tokens,e.total_tokens+=t.total_tokens);return e},bs=function(e){if(e.n!=null&&e.n>1)throw new x("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},xs=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};class Qt extends Ss{static runTools(e,t,n){const r=new Qt,a={...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"runTools"}};return r._run(()=>r._runTools(e,t,a)),r}_addMessage(e,t=!0){super._addMessage(e,t),lt(e)&&e.content&&this._emit("content",e.content)}}const As=1,vs=2,Cs=4,Is=8,Rs=16,$s=32,ks=64,Os=128,Es=256,Ps=Os|Es,Ts=Rs|$s|Ps|ks,Ms=As|vs|Ts,Ns=Cs|Is,ma=Ms|Ns,W={STR:As,NUM:vs,ARR:Cs,OBJ:Is,NULL:Rs,BOOL:$s,NAN:ks,INFINITY:Os,MINUS_INFINITY:Es,INF:Ps,SPECIAL:Ts,ATOM:Ms,COLLECTION:Ns,ALL:ma};class pa extends Error{}class ga extends Error{}function _a(s,e=W.ALL){if(typeof s!="string")throw new TypeError(`expecting str, got ${typeof s}`);if(!s.trim())throw new Error(`${s} is empty`);return ya(s.trim(),e)}const ya=(s,e)=>{const t=s.length;let n=0;const r=g=>{throw new pa(`${g} at position ${n}`)},a=g=>{throw new ga(`${g} at position ${n}`)},i=()=>(h(),n>=t&&r("Unexpected end of input"),s[n]==='"'?o():s[n]==="{"?l():s[n]==="["?u():s.substring(n,n+4)==="null"||W.NULL&e&&t-n<4&&"null".startsWith(s.substring(n))?(n+=4,null):s.substring(n,n+4)==="true"||W.BOOL&e&&t-n<4&&"true".startsWith(s.substring(n))?(n+=4,!0):s.substring(n,n+5)==="false"||W.BOOL&e&&t-n<5&&"false".startsWith(s.substring(n))?(n+=5,!1):s.substring(n,n+8)==="Infinity"||W.INFINITY&e&&t-n<8&&"Infinity".startsWith(s.substring(n))?(n+=8,1/0):s.substring(n,n+9)==="-Infinity"||W.MINUS_INFINITY&e&&1<t-n&&t-n<9&&"-Infinity".startsWith(s.substring(n))?(n+=9,-1/0):s.substring(n,n+3)==="NaN"||W.NAN&e&&t-n<3&&"NaN".startsWith(s.substring(n))?(n+=3,NaN):m()),o=()=>{const g=n;let d=!1;for(n++;n<t&&(s[n]!=='"'||d&&s[n-1]==="\\");)d=s[n]==="\\"?!d:!1,n++;if(s.charAt(n)=='"')try{return JSON.parse(s.substring(g,++n-Number(d)))}catch(b){a(String(b))}else if(W.STR&e)try{return JSON.parse(s.substring(g,n-Number(d))+'"')}catch{return JSON.parse(s.substring(g,s.lastIndexOf("\\"))+'"')}r("Unterminated string literal")},l=()=>{n++,h();const g={};try{for(;s[n]!=="}";){if(h(),n>=t&&W.OBJ&e)return g;const d=o();h(),n++;try{const b=i();Object.defineProperty(g,d,{value:b,writable:!0,enumerable:!0,configurable:!0})}catch(b){if(W.OBJ&e)return g;throw b}h(),s[n]===","&&n++}}catch{if(W.OBJ&e)return g;r("Expected '}' at end of object")}return n++,g},u=()=>{n++;const g=[];try{for(;s[n]!=="]";)g.push(i()),h(),s[n]===","&&n++}catch{if(W.ARR&e)return g;r("Expected ']' at end of array")}return n++,g},m=()=>{if(n===0){s==="-"&&W.NUM&e&&r("Not sure what '-' is");try{return JSON.parse(s)}catch(d){if(W.NUM&e)try{return s[s.length-1]==="."?JSON.parse(s.substring(0,s.lastIndexOf("."))):JSON.parse(s.substring(0,s.lastIndexOf("e")))}catch{}a(String(d))}}const g=n;for(s[n]==="-"&&n++;s[n]&&!",]}".includes(s[n]);)n++;n==t&&!(W.NUM&e)&&r("Unterminated number literal");try{return JSON.parse(s.substring(g,n))}catch{s.substring(g,n)==="-"&&W.NUM&e&&r("Not sure what '-' is");try{return JSON.parse(s.substring(g,s.lastIndexOf("e")))}catch(b){a(String(b))}}},h=()=>{for(;n<t&&`
|
|
10
|
+
\r `.includes(s[n]);)n++};return i()},On=s=>_a(s,W.ALL^W.NUM);var D,re,pe,oe,Ct,Xe,It,Rt,$t,Ke,kt,En;class De extends Ss{constructor(e){super(),D.add(this),re.set(this,void 0),pe.set(this,void 0),oe.set(this,void 0),R(this,re,e),R(this,pe,[])}get currentChatCompletionSnapshot(){return c(this,oe,"f")}static fromReadableStream(e){const t=new De(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,n){const r=new De(t);return r._run(()=>r._runChatCompletion(e,{...t,stream:!0},{...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"stream"}})),r}async _createChatCompletion(e,t,n){var i;super._createChatCompletion;const r=n==null?void 0:n.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),c(this,D,"m",Ct).call(this);const a=await e.chat.completions.create({...t,stream:!0},{...n,signal:this.controller.signal});this._connected();for await(const o of a)c(this,D,"m",It).call(this,o);if((i=a.controller.signal)!=null&&i.aborted)throw new z;return this._addChatCompletion(c(this,D,"m",Ke).call(this))}async _fromReadableStream(e,t){var i;const n=t==null?void 0:t.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),c(this,D,"m",Ct).call(this),this._connected();const r=ne.fromReadableStream(e,this.controller);let a;for await(const o of r)a&&a!==o.id&&this._addChatCompletion(c(this,D,"m",Ke).call(this)),c(this,D,"m",It).call(this,o),a=o.id;if((i=r.controller.signal)!=null&&i.aborted)throw new z;return this._addChatCompletion(c(this,D,"m",Ke).call(this))}[(re=new WeakMap,pe=new WeakMap,oe=new WeakMap,D=new WeakSet,Ct=function(){this.ended||R(this,oe,void 0)},Xe=function(t){let n=c(this,pe,"f")[t.index];return n||(n={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},c(this,pe,"f")[t.index]=n,n)},It=function(t){var r,a,i,o,l,u,m,h,g,d,b,w,v,E,p;if(this.ended)return;const n=c(this,D,"m",En).call(this,t);this._emit("chunk",t,n);for(const y of t.choices){const _=n.choices[y.index];y.delta.content!=null&&((r=_.message)==null?void 0:r.role)==="assistant"&&((a=_.message)!=null&&a.content)&&(this._emit("content",y.delta.content,_.message.content),this._emit("content.delta",{delta:y.delta.content,snapshot:_.message.content,parsed:_.message.parsed})),y.delta.refusal!=null&&((i=_.message)==null?void 0:i.role)==="assistant"&&((o=_.message)!=null&&o.refusal)&&this._emit("refusal.delta",{delta:y.delta.refusal,snapshot:_.message.refusal}),((l=y.logprobs)==null?void 0:l.content)!=null&&((u=_.message)==null?void 0:u.role)==="assistant"&&this._emit("logprobs.content.delta",{content:(m=y.logprobs)==null?void 0:m.content,snapshot:((h=_.logprobs)==null?void 0:h.content)??[]}),((g=y.logprobs)==null?void 0:g.refusal)!=null&&((d=_.message)==null?void 0:d.role)==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:(b=y.logprobs)==null?void 0:b.refusal,snapshot:((w=_.logprobs)==null?void 0:w.refusal)??[]});const C=c(this,D,"m",Xe).call(this,_);_.finish_reason&&(c(this,D,"m",$t).call(this,_),C.current_tool_call_index!=null&&c(this,D,"m",Rt).call(this,_,C.current_tool_call_index));for(const k of y.delta.tool_calls??[])C.current_tool_call_index!==k.index&&(c(this,D,"m",$t).call(this,_),C.current_tool_call_index!=null&&c(this,D,"m",Rt).call(this,_,C.current_tool_call_index)),C.current_tool_call_index=k.index;for(const k of y.delta.tool_calls??[]){const $=(v=_.message.tool_calls)==null?void 0:v[k.index];$!=null&&$.type&&(($==null?void 0:$.type)==="function"?this._emit("tool_calls.function.arguments.delta",{name:(E=$.function)==null?void 0:E.name,index:k.index,arguments:$.function.arguments,parsed_arguments:$.function.parsed_arguments,arguments_delta:((p=k.function)==null?void 0:p.arguments)??""}):($==null||$.type,void 0))}}},Rt=function(t,n){var i,o,l;if(c(this,D,"m",Xe).call(this,t).done_tool_calls.has(n))return;const a=(i=t.message.tool_calls)==null?void 0:i[n];if(!a)throw new Error("no tool call snapshot");if(!a.type)throw new Error("tool call snapshot missing `type`");if(a.type==="function"){const u=(l=(o=c(this,re,"f"))==null?void 0:o.tools)==null?void 0:l.find(m=>ct(m)&&m.function.name===a.function.name);this._emit("tool_calls.function.arguments.done",{name:a.function.name,index:n,arguments:a.function.arguments,parsed_arguments:We(u)?u.$parseRaw(a.function.arguments):u!=null&&u.function.strict?JSON.parse(a.function.arguments):null})}else a.type},$t=function(t){var r,a;const n=c(this,D,"m",Xe).call(this,t);if(t.message.content&&!n.content_done){n.content_done=!0;const i=c(this,D,"m",kt).call(this);this._emit("content.done",{content:t.message.content,parsed:i?i.$parseRaw(t.message.content):null})}t.message.refusal&&!n.refusal_done&&(n.refusal_done=!0,this._emit("refusal.done",{refusal:t.message.refusal})),(r=t.logprobs)!=null&&r.content&&!n.logprobs_content_done&&(n.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:t.logprobs.content})),(a=t.logprobs)!=null&&a.refusal&&!n.logprobs_refusal_done&&(n.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:t.logprobs.refusal}))},Ke=function(){if(this.ended)throw new x("stream has ended, this shouldn't happen");const t=c(this,oe,"f");if(!t)throw new x("request ended without sending any chunks");return R(this,oe,void 0),R(this,pe,[]),wa(t,c(this,re,"f"))},kt=function(){var n;const t=(n=c(this,re,"f"))==null?void 0:n.response_format;return Kt(t)?t:null},En=function(t){var n,r,a,i;let o=c(this,oe,"f");const{choices:l,...u}=t;o?Object.assign(o,u):o=R(this,oe,{...u,choices:[]});for(const{delta:m,finish_reason:h,index:g,logprobs:d=null,...b}of t.choices){let w=o.choices[g];if(w||(w=o.choices[g]={finish_reason:h,index:g,message:{},logprobs:d,...b}),d)if(!w.logprobs)w.logprobs=Object.assign({},d);else{const{content:k,refusal:$,...F}=d;Object.assign(w.logprobs,F),k&&((n=w.logprobs).content??(n.content=[]),w.logprobs.content.push(...k)),$&&((r=w.logprobs).refusal??(r.refusal=[]),w.logprobs.refusal.push(...$))}if(h&&(w.finish_reason=h,c(this,re,"f")&&gs(c(this,re,"f")))){if(h==="length")throw new Yn;if(h==="content_filter")throw new Zn}if(Object.assign(w,b),!m)continue;const{content:v,refusal:E,function_call:p,role:y,tool_calls:_,...C}=m;if(Object.assign(w.message,C),E&&(w.message.refusal=(w.message.refusal||"")+E),y&&(w.message.role=y),p&&(w.message.function_call?(p.name&&(w.message.function_call.name=p.name),p.arguments&&((a=w.message.function_call).arguments??(a.arguments=""),w.message.function_call.arguments+=p.arguments)):w.message.function_call=p),v&&(w.message.content=(w.message.content||"")+v,!w.message.refusal&&c(this,D,"m",kt).call(this)&&(w.message.parsed=On(w.message.content))),_){w.message.tool_calls||(w.message.tool_calls=[]);for(const{index:k,id:$,type:F,function:A,...T}of _){const M=(i=w.message.tool_calls)[k]??(i[k]={});Object.assign(M,T),$&&(M.id=$),F&&(M.type=F),A&&(M.function??(M.function={name:A.name??"",arguments:""})),A!=null&&A.name&&(M.function.name=A.name),A!=null&&A.arguments&&(M.function.arguments+=A.arguments,ua(c(this,re,"f"),M)&&(M.function.parsed_arguments=On(M.function.arguments)))}}}return o},Symbol.asyncIterator)](){const e=[],t=[];let n=!1;return this.on("chunk",r=>{const a=t.shift();a?a.resolve(r):e.push(r)}),this.on("end",()=>{n=!0;for(const r of t)r.resolve(void 0);t.length=0}),this.on("abort",r=>{n=!0;for(const a of t)a.reject(r);t.length=0}),this.on("error",r=>{n=!0;for(const a of t)a.reject(r);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((a,i)=>t.push({resolve:a,reject:i})).then(a=>a?{value:a,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new ne(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function wa(s,e){const{id:t,choices:n,created:r,model:a,system_fingerprint:i,...o}=s,l={...o,id:t,choices:n.map(({message:u,finish_reason:m,index:h,logprobs:g,...d})=>{if(!m)throw new x(`missing finish_reason for choice ${h}`);const{content:b=null,function_call:w,tool_calls:v,...E}=u,p=u.role;if(!p)throw new x(`missing role for choice ${h}`);if(w){const{arguments:y,name:_}=w;if(y==null)throw new x(`missing function_call.arguments for choice ${h}`);if(!_)throw new x(`missing function_call.name for choice ${h}`);return{...d,message:{content:b,function_call:{arguments:y,name:_},role:p,refusal:u.refusal??null},finish_reason:m,index:h,logprobs:g}}return v?{...d,index:h,finish_reason:m,logprobs:g,message:{...E,role:p,content:b,refusal:u.refusal??null,tool_calls:v.map((y,_)=>{const{function:C,type:k,id:$,...F}=y,{arguments:A,name:T,...M}=C||{};if($==null)throw new x(`missing choices[${h}].tool_calls[${_}].id
|
|
11
|
+
${Ve(s)}`);if(k==null)throw new x(`missing choices[${h}].tool_calls[${_}].type
|
|
12
|
+
${Ve(s)}`);if(T==null)throw new x(`missing choices[${h}].tool_calls[${_}].function.name
|
|
13
|
+
${Ve(s)}`);if(A==null)throw new x(`missing choices[${h}].tool_calls[${_}].function.arguments
|
|
14
|
+
${Ve(s)}`);return{...F,id:$,type:k,function:{...M,name:T,arguments:A}}})}}:{...d,message:{...E,content:b,role:p,refusal:u.refusal??null},finish_reason:m,index:h,logprobs:g}}),created:r,model:a,object:"chat.completion",...i?{system_fingerprint:i}:{}};return oa(l,e)}function Ve(s){return JSON.stringify(s)}class ft extends De{static fromReadableStream(e){const t=new ft(null);return t._run(()=>t._fromReadableStream(e)),t}static runTools(e,t,n){const r=new ft(t),a={...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"runTools"}};return r._run(()=>r._runTools(e,t,a)),r}}let zt=class extends I{constructor(){super(...arguments),this.messages=new ps(this._client)}create(e,t){return this._client.post("/chat/completions",{body:e,...t,stream:e.stream??!1})}retrieve(e,t){return this._client.get(f`/chat/completions/${e}`,t)}update(e,t,n){return this._client.post(f`/chat/completions/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList("/chat/completions",L,{query:e,...t})}delete(e,t){return this._client.delete(f`/chat/completions/${e}`,t)}parse(e,t){return ha(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t==null?void 0:t.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(n=>Vt(n,e))}runTools(e,t){return e.stream?ft.runTools(this._client,e,t):Qt.runTools(this._client,e,t)}stream(e,t){return De.createChatCompletion(this._client,e,t)}};zt.Messages=ps;class Yt extends I{constructor(){super(...arguments),this.completions=new zt(this._client)}}Yt.Completions=zt;const js=Symbol("brand.privateNullableHeaders");function*ba(s){if(!s)return;if(js in s){const{values:n,nulls:r}=s;yield*n.entries();for(const a of r)yield[a,null];return}let e=!1,t;s instanceof Headers?t=s.entries():gn(s)?t=s:(e=!0,t=Object.entries(s??{}));for(let n of t){const r=n[0];if(typeof r!="string")throw new TypeError("expected header name to be a string");const a=gn(n[1])?n[1]:[n[1]];let i=!1;for(const o of a)o!==void 0&&(e&&!i&&(i=!0,yield[r,null]),yield[r,o])}}const S=s=>{const e=new Headers,t=new Set;for(const n of s){const r=new Set;for(const[a,i]of ba(n)){const o=a.toLowerCase();r.has(o)||(e.delete(a),r.add(o)),i===null?(e.delete(a),t.add(o)):(e.append(a,i),t.delete(o))}}return{[js]:!0,values:e,nulls:t}};class Fs extends I{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:S([{Accept:"application/octet-stream"},t==null?void 0:t.headers]),__binaryResponse:!0})}}class Ls extends I{create(e,t){return this._client.post("/audio/transcriptions",fe({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}}class Ds extends I{create(e,t){return this._client.post("/audio/translations",fe({body:e,...t,__metadata:{model:e.model}},this._client))}}class Ue extends I{constructor(){super(...arguments),this.transcriptions=new Ls(this._client),this.translations=new Ds(this._client),this.speech=new Fs(this._client)}}Ue.Transcriptions=Ls;Ue.Translations=Ds;Ue.Speech=Fs;class Bs extends I{create(e,t){return this._client.post("/batches",{body:e,...t})}retrieve(e,t){return this._client.get(f`/batches/${e}`,t)}list(e={},t){return this._client.getAPIList("/batches",L,{query:e,...t})}cancel(e,t){return this._client.post(f`/batches/${e}/cancel`,t)}}class Ws extends I{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:S([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers])})}retrieve(e,t){return this._client.get(f`/assistants/${e}`,{...t,headers:S([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers])})}update(e,t,n){return this._client.post(f`/assistants/${e}`,{body:t,...n,headers:S([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}list(e={},t){return this._client.getAPIList("/assistants",L,{query:e,...t,headers:S([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers])})}delete(e,t){return this._client.delete(f`/assistants/${e}`,{...t,headers:S([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers])})}}class Us extends I{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:S([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers])})}}class qs extends I{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:S([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers])})}}let wt=class extends I{constructor(){super(...arguments),this.sessions=new Us(this._client),this.transcriptionSessions=new qs(this._client)}};wt.Sessions=Us;wt.TranscriptionSessions=qs;class Js extends I{create(e,t,n){return this._client.post(f`/threads/${e}/messages`,{body:t,...n,headers:S([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}retrieve(e,t,n){const{thread_id:r}=t;return this._client.get(f`/threads/${r}/messages/${e}`,{...n,headers:S([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}update(e,t,n){const{thread_id:r,...a}=t;return this._client.post(f`/threads/${r}/messages/${e}`,{body:a,...n,headers:S([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}list(e,t={},n){return this._client.getAPIList(f`/threads/${e}/messages`,L,{query:t,...n,headers:S([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}delete(e,t,n){const{thread_id:r}=t;return this._client.delete(f`/threads/${r}/messages/${e}`,{...n,headers:S([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}}class Hs extends I{retrieve(e,t,n){const{thread_id:r,run_id:a,...i}=t;return this._client.get(f`/threads/${r}/runs/${a}/steps/${e}`,{query:i,...n,headers:S([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}list(e,t,n){const{thread_id:r,...a}=t;return this._client.getAPIList(f`/threads/${r}/runs/${e}/steps`,L,{query:a,...n,headers:S([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}}const xa=s=>{if(typeof Buffer<"u"){const e=Buffer.from(s,"base64");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{const e=atob(s),t=e.length,n=new Uint8Array(t);for(let r=0;r<t;r++)n[r]=e.charCodeAt(r);return Array.from(new Float32Array(n.buffer))}};var Ot={};const ge=s=>{var e,t,n,r;if(typeof globalThis.process<"u")return((e=Ot==null?void 0:Ot[s])==null?void 0:e.trim())??void 0;if(typeof globalThis.Deno<"u")return(r=(n=(t=globalThis.Deno.env)==null?void 0:t.get)==null?void 0:n.call(t,s))==null?void 0:r.trim()};var J,he,Wt,te,nt,Y,de,Se,ue,mt,Q,st,rt,Fe,Me,Ne,Pn,Tn,Mn,Nn,jn,Fn,Ln;class Le extends Gt{constructor(){super(...arguments),J.add(this),Wt.set(this,[]),te.set(this,{}),nt.set(this,{}),Y.set(this,void 0),de.set(this,void 0),Se.set(this,void 0),ue.set(this,void 0),mt.set(this,void 0),Q.set(this,void 0),st.set(this,void 0),rt.set(this,void 0),Fe.set(this,void 0)}[(Wt=new WeakMap,te=new WeakMap,nt=new WeakMap,Y=new WeakMap,de=new WeakMap,Se=new WeakMap,ue=new WeakMap,mt=new WeakMap,Q=new WeakMap,st=new WeakMap,rt=new WeakMap,Fe=new WeakMap,J=new WeakSet,Symbol.asyncIterator)](){const e=[],t=[];let n=!1;return this.on("event",r=>{const a=t.shift();a?a.resolve(r):e.push(r)}),this.on("end",()=>{n=!0;for(const r of t)r.resolve(void 0);t.length=0}),this.on("abort",r=>{n=!0;for(const a of t)a.reject(r);t.length=0}),this.on("error",r=>{n=!0;for(const a of t)a.reject(r);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((a,i)=>t.push({resolve:a,reject:i})).then(a=>a?{value:a,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){const t=new he;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){var a;const n=t==null?void 0:t.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),this._connected();const r=ne.fromReadableStream(e,this.controller);for await(const i of r)c(this,J,"m",Me).call(this,i);if((a=r.controller.signal)!=null&&a.aborted)throw new z;return this._addRun(c(this,J,"m",Ne).call(this))}toReadableStream(){return new ne(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,n,r){const a=new he;return a._run(()=>a._runToolAssistantStream(e,t,n,{...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"stream"}})),a}async _createToolAssistantStream(e,t,n,r){var l;const a=r==null?void 0:r.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener("abort",()=>this.controller.abort()));const i={...n,stream:!0},o=await e.submitToolOutputs(t,i,{...r,signal:this.controller.signal});this._connected();for await(const u of o)c(this,J,"m",Me).call(this,u);if((l=o.controller.signal)!=null&&l.aborted)throw new z;return this._addRun(c(this,J,"m",Ne).call(this))}static createThreadAssistantStream(e,t,n){const r=new he;return r._run(()=>r._threadAssistantStream(e,t,{...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"stream"}})),r}static createAssistantStream(e,t,n,r){const a=new he;return a._run(()=>a._runAssistantStream(e,t,n,{...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"stream"}})),a}currentEvent(){return c(this,st,"f")}currentRun(){return c(this,rt,"f")}currentMessageSnapshot(){return c(this,Y,"f")}currentRunStepSnapshot(){return c(this,Fe,"f")}async finalRunSteps(){return await this.done(),Object.values(c(this,te,"f"))}async finalMessages(){return await this.done(),Object.values(c(this,nt,"f"))}async finalRun(){if(await this.done(),!c(this,de,"f"))throw Error("Final run was not received.");return c(this,de,"f")}async _createThreadAssistantStream(e,t,n){var o;const r=n==null?void 0:n.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort()));const a={...t,stream:!0},i=await e.createAndRun(a,{...n,signal:this.controller.signal});this._connected();for await(const l of i)c(this,J,"m",Me).call(this,l);if((o=i.controller.signal)!=null&&o.aborted)throw new z;return this._addRun(c(this,J,"m",Ne).call(this))}async _createAssistantStream(e,t,n,r){var l;const a=r==null?void 0:r.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener("abort",()=>this.controller.abort()));const i={...n,stream:!0},o=await e.create(t,i,{...r,signal:this.controller.signal});this._connected();for await(const u of o)c(this,J,"m",Me).call(this,u);if((l=o.controller.signal)!=null&&l.aborted)throw new z;return this._addRun(c(this,J,"m",Ne).call(this))}static accumulateDelta(e,t){for(const[n,r]of Object.entries(t)){if(!e.hasOwnProperty(n)){e[n]=r;continue}let a=e[n];if(a==null){e[n]=r;continue}if(n==="index"||n==="type"){e[n]=r;continue}if(typeof a=="string"&&typeof r=="string")a+=r;else if(typeof a=="number"&&typeof r=="number")a+=r;else if(St(a)&&St(r))a=this.accumulateDelta(a,r);else if(Array.isArray(a)&&Array.isArray(r)){if(a.every(i=>typeof i=="string"||typeof i=="number")){a.push(...r);continue}for(const i of r){if(!St(i))throw new Error(`Expected array delta entry to be an object but got: ${i}`);const o=i.index;if(o==null)throw console.error(i),new Error("Expected array delta entry to have an `index` property");if(typeof o!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${o}`);const l=a[o];l==null?a.push(i):a[o]=this.accumulateDelta(l,i)}continue}else throw Error(`Unhandled record type: ${n}, deltaValue: ${r}, accValue: ${a}`);e[n]=a}return e}_addRun(e){return e}async _threadAssistantStream(e,t,n){return await this._createThreadAssistantStream(t,e,n)}async _runAssistantStream(e,t,n,r){return await this._createAssistantStream(t,e,n,r)}async _runToolAssistantStream(e,t,n,r){return await this._createToolAssistantStream(t,e,n,r)}}he=Le,Me=function(e){if(!this.ended)switch(R(this,st,e),c(this,J,"m",Mn).call(this,e),e.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":c(this,J,"m",Ln).call(this,e);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":c(this,J,"m",Tn).call(this,e);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":c(this,J,"m",Pn).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},Ne=function(){if(this.ended)throw new x("stream has ended, this shouldn't happen");if(!c(this,de,"f"))throw Error("Final run has not been received");return c(this,de,"f")},Pn=function(e){const[t,n]=c(this,J,"m",jn).call(this,e,c(this,Y,"f"));R(this,Y,t),c(this,nt,"f")[t.id]=t;for(const r of n){const a=t.content[r.index];(a==null?void 0:a.type)=="text"&&this._emit("textCreated",a.text)}switch(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,t),e.data.delta.content)for(const r of e.data.delta.content){if(r.type=="text"&&r.text){let a=r.text,i=t.content[r.index];if(i&&i.type=="text")this._emit("textDelta",a,i.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(r.index!=c(this,Se,"f")){if(c(this,ue,"f"))switch(c(this,ue,"f").type){case"text":this._emit("textDone",c(this,ue,"f").text,c(this,Y,"f"));break;case"image_file":this._emit("imageFileDone",c(this,ue,"f").image_file,c(this,Y,"f"));break}R(this,Se,r.index)}R(this,ue,t.content[r.index])}break;case"thread.message.completed":case"thread.message.incomplete":if(c(this,Se,"f")!==void 0){const r=e.data.content[c(this,Se,"f")];if(r)switch(r.type){case"image_file":this._emit("imageFileDone",r.image_file,c(this,Y,"f"));break;case"text":this._emit("textDone",r.text,c(this,Y,"f"));break}}c(this,Y,"f")&&this._emit("messageDone",e.data),R(this,Y,void 0)}},Tn=function(e){const t=c(this,J,"m",Nn).call(this,e);switch(R(this,Fe,t),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":const n=e.data.delta;if(n.step_details&&n.step_details.type=="tool_calls"&&n.step_details.tool_calls&&t.step_details.type=="tool_calls")for(const a of n.step_details.tool_calls)a.index==c(this,mt,"f")?this._emit("toolCallDelta",a,t.step_details.tool_calls[a.index]):(c(this,Q,"f")&&this._emit("toolCallDone",c(this,Q,"f")),R(this,mt,a.index),R(this,Q,t.step_details.tool_calls[a.index]),c(this,Q,"f")&&this._emit("toolCallCreated",c(this,Q,"f")));this._emit("runStepDelta",e.data.delta,t);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":R(this,Fe,void 0),e.data.step_details.type=="tool_calls"&&c(this,Q,"f")&&(this._emit("toolCallDone",c(this,Q,"f")),R(this,Q,void 0)),this._emit("runStepDone",e.data,t);break}},Mn=function(e){c(this,Wt,"f").push(e),this._emit("event",e)},Nn=function(e){switch(e.event){case"thread.run.step.created":return c(this,te,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=c(this,te,"f")[e.data.id];if(!t)throw Error("Received a RunStepDelta before creation of a snapshot");let n=e.data;if(n.delta){const r=he.accumulateDelta(t,n.delta);c(this,te,"f")[e.data.id]=r}return c(this,te,"f")[e.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":c(this,te,"f")[e.data.id]=e.data;break}if(c(this,te,"f")[e.data.id])return c(this,te,"f")[e.data.id];throw new Error("No snapshot available")},jn=function(e,t){let n=[];switch(e.event){case"thread.message.created":return[e.data,n];case"thread.message.delta":if(!t)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let r=e.data;if(r.delta.content)for(const a of r.delta.content)if(a.index in t.content){let i=t.content[a.index];t.content[a.index]=c(this,J,"m",Fn).call(this,a,i)}else t.content[a.index]=a,n.push(a);return[t,n];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(t)return[t,n];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},Fn=function(e,t){return he.accumulateDelta(t,e)},Ln=function(e){switch(R(this,rt,e.data),e.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":case"thread.run.incomplete":R(this,de,e.data),c(this,Q,"f")&&(this._emit("toolCallDone",c(this,Q,"f")),R(this,Q,void 0));break}};let Zt=class extends I{constructor(){super(...arguments),this.steps=new Hs(this._client)}create(e,t,n){const{include:r,...a}=t;return this._client.post(f`/threads/${e}/runs`,{query:{include:r},body:a,...n,headers:S([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers]),stream:t.stream??!1})}retrieve(e,t,n){const{thread_id:r}=t;return this._client.get(f`/threads/${r}/runs/${e}`,{...n,headers:S([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}update(e,t,n){const{thread_id:r,...a}=t;return this._client.post(f`/threads/${r}/runs/${e}`,{body:a,...n,headers:S([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}list(e,t={},n){return this._client.getAPIList(f`/threads/${e}/runs`,L,{query:t,...n,headers:S([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}cancel(e,t,n){const{thread_id:r}=t;return this._client.post(f`/threads/${r}/runs/${e}/cancel`,{...n,headers:S([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}async createAndPoll(e,t,n){const r=await this.create(e,t,n);return await this.poll(r.id,{thread_id:e},n)}createAndStream(e,t,n){return Le.createAssistantStream(e,this._client.beta.threads.runs,t,n)}async poll(e,t,n){var a;const r=S([n==null?void 0:n.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":((a=n==null?void 0:n.pollIntervalMs)==null?void 0:a.toString())??void 0}]);for(;;){const{data:i,response:o}=await this.retrieve(e,t,{...n,headers:{...n==null?void 0:n.headers,...r}}).withResponse();switch(i.status){case"queued":case"in_progress":case"cancelling":let l=5e3;if(n!=null&&n.pollIntervalMs)l=n.pollIntervalMs;else{const u=o.headers.get("openai-poll-after-ms");if(u){const m=parseInt(u);isNaN(m)||(l=m)}}await Be(l);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return i}}}stream(e,t,n){return Le.createAssistantStream(e,this._client.beta.threads.runs,t,n)}submitToolOutputs(e,t,n){const{thread_id:r,...a}=t;return this._client.post(f`/threads/${r}/runs/${e}/submit_tool_outputs`,{body:a,...n,headers:S([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers]),stream:t.stream??!1})}async submitToolOutputsAndPoll(e,t,n){const r=await this.submitToolOutputs(e,t,n);return await this.poll(r.id,t,n)}submitToolOutputsStream(e,t,n){return Le.createToolAssistantStream(e,this._client.beta.threads.runs,t,n)}};Zt.Steps=Hs;class bt extends I{constructor(){super(...arguments),this.runs=new Zt(this._client),this.messages=new Js(this._client)}create(e={},t){return this._client.post("/threads",{body:e,...t,headers:S([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers])})}retrieve(e,t){return this._client.get(f`/threads/${e}`,{...t,headers:S([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers])})}update(e,t,n){return this._client.post(f`/threads/${e}`,{body:t,...n,headers:S([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}delete(e,t){return this._client.delete(f`/threads/${e}`,{...t,headers:S([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers])})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:S([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers]),stream:e.stream??!1})}async createAndRunPoll(e,t){const n=await this.createAndRun(e,t);return await this.runs.poll(n.id,{thread_id:n.thread_id},t)}createAndRunStream(e,t){return Le.createThreadAssistantStream(e,this._client.beta.threads,t)}}bt.Runs=Zt;bt.Messages=Js;class qe extends I{constructor(){super(...arguments),this.realtime=new wt(this._client),this.assistants=new Ws(this._client),this.threads=new bt(this._client)}}qe.Realtime=wt;qe.Assistants=Ws;qe.Threads=bt;class Xs extends I{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}}class Ks extends I{retrieve(e,t,n){const{container_id:r}=t;return this._client.get(f`/containers/${r}/files/${e}/content`,{...n,headers:S([{Accept:"application/binary"},n==null?void 0:n.headers]),__binaryResponse:!0})}}let en=class extends I{constructor(){super(...arguments),this.content=new Ks(this._client)}create(e,t,n){return this._client.post(f`/containers/${e}/files`,fe({body:t,...n},this._client))}retrieve(e,t,n){const{container_id:r}=t;return this._client.get(f`/containers/${r}/files/${e}`,n)}list(e,t={},n){return this._client.getAPIList(f`/containers/${e}/files`,L,{query:t,...n})}delete(e,t,n){const{container_id:r}=t;return this._client.delete(f`/containers/${r}/files/${e}`,{...n,headers:S([{Accept:"*/*"},n==null?void 0:n.headers])})}};en.Content=Ks;class tn extends I{constructor(){super(...arguments),this.files=new en(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t})}retrieve(e,t){return this._client.get(f`/containers/${e}`,t)}list(e={},t){return this._client.getAPIList("/containers",L,{query:e,...t})}delete(e,t){return this._client.delete(f`/containers/${e}`,{...t,headers:S([{Accept:"*/*"},t==null?void 0:t.headers])})}}tn.Files=en;class Vs extends I{create(e,t,n){const{include:r,...a}=t;return this._client.post(f`/conversations/${e}/items`,{query:{include:r},body:a,...n})}retrieve(e,t,n){const{conversation_id:r,...a}=t;return this._client.get(f`/conversations/${r}/items/${e}`,{query:a,...n})}list(e,t={},n){return this._client.getAPIList(f`/conversations/${e}/items`,Yr,{query:t,...n})}delete(e,t,n){const{conversation_id:r}=t;return this._client.delete(f`/conversations/${r}/items/${e}`,n)}}class nn extends I{constructor(){super(...arguments),this.items=new Vs(this._client)}create(e={},t){return this._client.post("/conversations",{body:e,...t})}retrieve(e,t){return this._client.get(f`/conversations/${e}`,t)}update(e,t,n){return this._client.post(f`/conversations/${e}`,{body:t,...n})}delete(e,t){return this._client.delete(f`/conversations/${e}`,t)}}nn.Items=Vs;class Gs extends I{create(e,t){const n=!!e.encoding_format;let r=n?e.encoding_format:"base64";n&&q(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);const a=this._client.post("/embeddings",{body:{...e,encoding_format:r},...t});return n?a:(q(this._client).debug("embeddings/decoding base64 embeddings from base64"),a._thenUnwrap(i=>(i&&i.data&&i.data.forEach(o=>{const l=o.embedding;o.embedding=xa(l)}),i)))}}class Qs extends I{retrieve(e,t,n){const{eval_id:r,run_id:a}=t;return this._client.get(f`/evals/${r}/runs/${a}/output_items/${e}`,n)}list(e,t,n){const{eval_id:r,...a}=t;return this._client.getAPIList(f`/evals/${r}/runs/${e}/output_items`,L,{query:a,...n})}}class sn extends I{constructor(){super(...arguments),this.outputItems=new Qs(this._client)}create(e,t,n){return this._client.post(f`/evals/${e}/runs`,{body:t,...n})}retrieve(e,t,n){const{eval_id:r}=t;return this._client.get(f`/evals/${r}/runs/${e}`,n)}list(e,t={},n){return this._client.getAPIList(f`/evals/${e}/runs`,L,{query:t,...n})}delete(e,t,n){const{eval_id:r}=t;return this._client.delete(f`/evals/${r}/runs/${e}`,n)}cancel(e,t,n){const{eval_id:r}=t;return this._client.post(f`/evals/${r}/runs/${e}`,n)}}sn.OutputItems=Qs;class rn extends I{constructor(){super(...arguments),this.runs=new sn(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t})}retrieve(e,t){return this._client.get(f`/evals/${e}`,t)}update(e,t,n){return this._client.post(f`/evals/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList("/evals",L,{query:e,...t})}delete(e,t){return this._client.delete(f`/evals/${e}`,t)}}rn.Runs=sn;let zs=class extends I{create(e,t){return this._client.post("/files",fe({body:e,...t},this._client))}retrieve(e,t){return this._client.get(f`/files/${e}`,t)}list(e={},t){return this._client.getAPIList("/files",L,{query:e,...t})}delete(e,t){return this._client.delete(f`/files/${e}`,t)}content(e,t){return this._client.get(f`/files/${e}/content`,{...t,headers:S([{Accept:"application/binary"},t==null?void 0:t.headers]),__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:n=1800*1e3}={}){const r=new Set(["processed","error","deleted"]),a=Date.now();let i=await this.retrieve(e);for(;!i.status||!r.has(i.status);)if(await Be(t),i=await this.retrieve(e),Date.now()-a>n)throw new Jt({message:`Giving up on waiting for file ${e} to finish processing after ${n} milliseconds.`});return i}};class Ys extends I{}let Zs=class extends I{run(e,t){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...t})}validate(e,t){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...t})}};class an extends I{constructor(){super(...arguments),this.graders=new Zs(this._client)}}an.Graders=Zs;class er extends I{create(e,t,n){return this._client.getAPIList(f`/fine_tuning/checkpoints/${e}/permissions`,yt,{body:t,method:"post",...n})}retrieve(e,t={},n){return this._client.get(f`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...n})}delete(e,t,n){const{fine_tuned_model_checkpoint:r}=t;return this._client.delete(f`/fine_tuning/checkpoints/${r}/permissions/${e}`,n)}}let on=class extends I{constructor(){super(...arguments),this.permissions=new er(this._client)}};on.Permissions=er;class tr extends I{list(e,t={},n){return this._client.getAPIList(f`/fine_tuning/jobs/${e}/checkpoints`,L,{query:t,...n})}}class cn extends I{constructor(){super(...arguments),this.checkpoints=new tr(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this._client.get(f`/fine_tuning/jobs/${e}`,t)}list(e={},t){return this._client.getAPIList("/fine_tuning/jobs",L,{query:e,...t})}cancel(e,t){return this._client.post(f`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},n){return this._client.getAPIList(f`/fine_tuning/jobs/${e}/events`,L,{query:t,...n})}pause(e,t){return this._client.post(f`/fine_tuning/jobs/${e}/pause`,t)}resume(e,t){return this._client.post(f`/fine_tuning/jobs/${e}/resume`,t)}}cn.Checkpoints=tr;class Ae extends I{constructor(){super(...arguments),this.methods=new Ys(this._client),this.jobs=new cn(this._client),this.checkpoints=new on(this._client),this.alpha=new an(this._client)}}Ae.Methods=Ys;Ae.Jobs=cn;Ae.Checkpoints=on;Ae.Alpha=an;class nr extends I{}class ln extends I{constructor(){super(...arguments),this.graderModels=new nr(this._client)}}ln.GraderModels=nr;class sr extends I{createVariation(e,t){return this._client.post("/images/variations",fe({body:e,...t},this._client))}edit(e,t){return this._client.post("/images/edits",fe({body:e,...t,stream:e.stream??!1},this._client))}generate(e,t){return this._client.post("/images/generations",{body:e,...t,stream:e.stream??!1})}}class rr extends I{retrieve(e,t){return this._client.get(f`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",yt,e)}delete(e,t){return this._client.delete(f`/models/${e}`,t)}}class ar extends I{create(e,t){return this._client.post("/moderations",{body:e,...t})}}class ir extends I{create(e,t){return this._client.post("/realtime/client_secrets",{body:e,...t})}}class un extends I{constructor(){super(...arguments),this.clientSecrets=new ir(this._client)}}un.ClientSecrets=ir;function Sa(s,e){return!e||!va(e)?{...s,output_parsed:null,output:s.output.map(t=>t.type==="function_call"?{...t,parsed_arguments:null}:t.type==="message"?{...t,content:t.content.map(n=>({...n,parsed:null}))}:t)}:or(s,e)}function or(s,e){const t=s.output.map(r=>{if(r.type==="function_call")return{...r,parsed_arguments:Ra(e,r)};if(r.type==="message"){const a=r.content.map(i=>i.type==="output_text"?{...i,parsed:Aa(e,i.text)}:i);return{...r,content:a}}return r}),n=Object.assign({},s,{output:t});return Object.getOwnPropertyDescriptor(s,"output_text")||Ut(n),Object.defineProperty(n,"output_parsed",{enumerable:!0,get(){for(const r of n.output)if(r.type==="message"){for(const a of r.content)if(a.type==="output_text"&&a.parsed!==null)return a.parsed}return null}}),n}function Aa(s,e){var t,n,r,a;return((n=(t=s.text)==null?void 0:t.format)==null?void 0:n.type)!=="json_schema"?null:"$parseRaw"in((r=s.text)==null?void 0:r.format)?((a=s.text)==null?void 0:a.format).$parseRaw(e):JSON.parse(e)}function va(s){var e;return!!Kt((e=s.text)==null?void 0:e.format)}function Ca(s){return(s==null?void 0:s.$brand)==="auto-parseable-tool"}function Ia(s,e){return s.find(t=>t.type==="function"&&t.name===e)}function Ra(s,e){const t=Ia(s.tools??[],e.name);return{...e,...e,parsed_arguments:Ca(t)?t.$parseRaw(e.arguments):t!=null&&t.strict?JSON.parse(e.arguments):null}}function Ut(s){const e=[];for(const t of s.output)if(t.type==="message")for(const n of t.content)n.type==="output_text"&&e.push(n.text);s.output_text=e.join("")}var _e,Ge,ce,Qe,Dn,Bn,Wn,Un;class hn extends Gt{constructor(e){super(),_e.add(this),Ge.set(this,void 0),ce.set(this,void 0),Qe.set(this,void 0),R(this,Ge,e)}static createResponse(e,t,n){const r=new hn(t);return r._run(()=>r._createOrRetrieveResponse(e,t,{...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"stream"}})),r}async _createOrRetrieveResponse(e,t,n){var o;const r=n==null?void 0:n.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),c(this,_e,"m",Dn).call(this);let a,i=null;"response_id"in t?(a=await e.responses.retrieve(t.response_id,{stream:!0},{...n,signal:this.controller.signal,stream:!0}),i=t.starting_after??null):a=await e.responses.create({...t,stream:!0},{...n,signal:this.controller.signal}),this._connected();for await(const l of a)c(this,_e,"m",Bn).call(this,l,i);if((o=a.controller.signal)!=null&&o.aborted)throw new z;return c(this,_e,"m",Wn).call(this)}[(Ge=new WeakMap,ce=new WeakMap,Qe=new WeakMap,_e=new WeakSet,Dn=function(){this.ended||R(this,ce,void 0)},Bn=function(t,n){if(this.ended)return;const r=(i,o)=>{(n==null||o.sequence_number>n)&&this._emit(i,o)},a=c(this,_e,"m",Un).call(this,t);switch(r("event",t),t.type){case"response.output_text.delta":{const i=a.output[t.output_index];if(!i)throw new x(`missing output at index ${t.output_index}`);if(i.type==="message"){const o=i.content[t.content_index];if(!o)throw new x(`missing content at index ${t.content_index}`);if(o.type!=="output_text")throw new x(`expected content to be 'output_text', got ${o.type}`);r("response.output_text.delta",{...t,snapshot:o.text})}break}case"response.function_call_arguments.delta":{const i=a.output[t.output_index];if(!i)throw new x(`missing output at index ${t.output_index}`);i.type==="function_call"&&r("response.function_call_arguments.delta",{...t,snapshot:i.arguments});break}default:r(t.type,t);break}},Wn=function(){if(this.ended)throw new x("stream has ended, this shouldn't happen");const t=c(this,ce,"f");if(!t)throw new x("request ended without sending any events");R(this,ce,void 0);const n=$a(t,c(this,Ge,"f"));return R(this,Qe,n),n},Un=function(t){var r;let n=c(this,ce,"f");if(!n){if(t.type!=="response.created")throw new x(`When snapshot hasn't been set yet, expected 'response.created' event, got ${t.type}`);return n=R(this,ce,t.response),n}switch(t.type){case"response.output_item.added":{n.output.push(t.item);break}case"response.content_part.added":{const a=n.output[t.output_index];if(!a)throw new x(`missing output at index ${t.output_index}`);const i=a.type,o=t.part;i==="message"&&o.type!=="reasoning_text"?a.content.push(o):i==="reasoning"&&o.type==="reasoning_text"&&(a.content||(a.content=[]),a.content.push(o));break}case"response.output_text.delta":{const a=n.output[t.output_index];if(!a)throw new x(`missing output at index ${t.output_index}`);if(a.type==="message"){const i=a.content[t.content_index];if(!i)throw new x(`missing content at index ${t.content_index}`);if(i.type!=="output_text")throw new x(`expected content to be 'output_text', got ${i.type}`);i.text+=t.delta}break}case"response.function_call_arguments.delta":{const a=n.output[t.output_index];if(!a)throw new x(`missing output at index ${t.output_index}`);a.type==="function_call"&&(a.arguments+=t.delta);break}case"response.reasoning_text.delta":{const a=n.output[t.output_index];if(!a)throw new x(`missing output at index ${t.output_index}`);if(a.type==="reasoning"){const i=(r=a.content)==null?void 0:r[t.content_index];if(!i)throw new x(`missing content at index ${t.content_index}`);if(i.type!=="reasoning_text")throw new x(`expected content to be 'reasoning_text', got ${i.type}`);i.text+=t.delta}break}case"response.completed":{R(this,ce,t.response);break}}return n},Symbol.asyncIterator)](){const e=[],t=[];let n=!1;return this.on("event",r=>{const a=t.shift();a?a.resolve(r):e.push(r)}),this.on("end",()=>{n=!0;for(const r of t)r.resolve(void 0);t.length=0}),this.on("abort",r=>{n=!0;for(const a of t)a.reject(r);t.length=0}),this.on("error",r=>{n=!0;for(const a of t)a.reject(r);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((a,i)=>t.push({resolve:a,reject:i})).then(a=>a?{value:a,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();const e=c(this,Qe,"f");if(!e)throw new x("stream ended without producing a ChatCompletion");return e}}function $a(s,e){return Sa(s,e)}class cr extends I{list(e,t={},n){return this._client.getAPIList(f`/responses/${e}/input_items`,L,{query:t,...n})}}class dn extends I{constructor(){super(...arguments),this.inputItems=new cr(this._client)}create(e,t){return this._client.post("/responses",{body:e,...t,stream:e.stream??!1})._thenUnwrap(n=>("object"in n&&n.object==="response"&&Ut(n),n))}retrieve(e,t={},n){return this._client.get(f`/responses/${e}`,{query:t,...n,stream:(t==null?void 0:t.stream)??!1})._thenUnwrap(r=>("object"in r&&r.object==="response"&&Ut(r),r))}delete(e,t){return this._client.delete(f`/responses/${e}`,{...t,headers:S([{Accept:"*/*"},t==null?void 0:t.headers])})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(n=>or(n,e))}stream(e,t){return hn.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(f`/responses/${e}/cancel`,t)}}dn.InputItems=cr;class lr extends I{create(e,t,n){return this._client.post(f`/uploads/${e}/parts`,fe({body:t,...n},this._client))}}class fn extends I{constructor(){super(...arguments),this.parts=new lr(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t})}cancel(e,t){return this._client.post(f`/uploads/${e}/cancel`,t)}complete(e,t,n){return this._client.post(f`/uploads/${e}/complete`,{body:t,...n})}}fn.Parts=lr;const ka=async s=>{const e=await Promise.allSettled(s),t=e.filter(r=>r.status==="rejected");if(t.length){for(const r of t)console.error(r.reason);throw new Error(`${t.length} promise(s) failed - see the above errors`)}const n=[];for(const r of e)r.status==="fulfilled"&&n.push(r.value);return n};class ur extends I{create(e,t,n){return this._client.post(f`/vector_stores/${e}/file_batches`,{body:t,...n,headers:S([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}retrieve(e,t,n){const{vector_store_id:r}=t;return this._client.get(f`/vector_stores/${r}/file_batches/${e}`,{...n,headers:S([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}cancel(e,t,n){const{vector_store_id:r}=t;return this._client.post(f`/vector_stores/${r}/file_batches/${e}/cancel`,{...n,headers:S([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}async createAndPoll(e,t,n){const r=await this.create(e,t);return await this.poll(e,r.id,n)}listFiles(e,t,n){const{vector_store_id:r,...a}=t;return this._client.getAPIList(f`/vector_stores/${r}/file_batches/${e}/files`,L,{query:a,...n,headers:S([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}async poll(e,t,n){var a;const r=S([n==null?void 0:n.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":((a=n==null?void 0:n.pollIntervalMs)==null?void 0:a.toString())??void 0}]);for(;;){const{data:i,response:o}=await this.retrieve(t,{vector_store_id:e},{...n,headers:r}).withResponse();switch(i.status){case"in_progress":let l=5e3;if(n!=null&&n.pollIntervalMs)l=n.pollIntervalMs;else{const u=o.headers.get("openai-poll-after-ms");if(u){const m=parseInt(u);isNaN(m)||(l=m)}}await Be(l);break;case"failed":case"cancelled":case"completed":return i}}}async uploadAndPoll(e,{files:t,fileIds:n=[]},r){if(t==null||t.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");const a=(r==null?void 0:r.maxConcurrency)??5,i=Math.min(a,t.length),o=this._client,l=t.values(),u=[...n];async function m(g){for(let d of g){const b=await o.files.create({file:d,purpose:"assistants"},r);u.push(b.id)}}const h=Array(i).fill(l).map(m);return await ka(h),await this.createAndPoll(e,{file_ids:u})}}class hr extends I{create(e,t,n){return this._client.post(f`/vector_stores/${e}/files`,{body:t,...n,headers:S([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}retrieve(e,t,n){const{vector_store_id:r}=t;return this._client.get(f`/vector_stores/${r}/files/${e}`,{...n,headers:S([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}update(e,t,n){const{vector_store_id:r,...a}=t;return this._client.post(f`/vector_stores/${r}/files/${e}`,{body:a,...n,headers:S([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}list(e,t={},n){return this._client.getAPIList(f`/vector_stores/${e}/files`,L,{query:t,...n,headers:S([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}delete(e,t,n){const{vector_store_id:r}=t;return this._client.delete(f`/vector_stores/${r}/files/${e}`,{...n,headers:S([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}async createAndPoll(e,t,n){const r=await this.create(e,t,n);return await this.poll(e,r.id,n)}async poll(e,t,n){var a;const r=S([n==null?void 0:n.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":((a=n==null?void 0:n.pollIntervalMs)==null?void 0:a.toString())??void 0}]);for(;;){const i=await this.retrieve(t,{vector_store_id:e},{...n,headers:r}).withResponse(),o=i.data;switch(o.status){case"in_progress":let l=5e3;if(n!=null&&n.pollIntervalMs)l=n.pollIntervalMs;else{const u=i.response.headers.get("openai-poll-after-ms");if(u){const m=parseInt(u);isNaN(m)||(l=m)}}await Be(l);break;case"failed":case"completed":return o}}}async upload(e,t,n){const r=await this._client.files.create({file:t,purpose:"assistants"},n);return this.create(e,{file_id:r.id},n)}async uploadAndPoll(e,t,n){const r=await this.upload(e,t,n);return await this.poll(e,r.id,n)}content(e,t,n){const{vector_store_id:r}=t;return this._client.getAPIList(f`/vector_stores/${r}/files/${e}/content`,yt,{...n,headers:S([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}}class xt extends I{constructor(){super(...arguments),this.files=new hr(this._client),this.fileBatches=new ur(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:S([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers])})}retrieve(e,t){return this._client.get(f`/vector_stores/${e}`,{...t,headers:S([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers])})}update(e,t,n){return this._client.post(f`/vector_stores/${e}`,{body:t,...n,headers:S([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}list(e={},t){return this._client.getAPIList("/vector_stores",L,{query:e,...t,headers:S([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers])})}delete(e,t){return this._client.delete(f`/vector_stores/${e}`,{...t,headers:S([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers])})}search(e,t,n){return this._client.getAPIList(f`/vector_stores/${e}/search`,yt,{body:t,method:"post",...n,headers:S([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}}xt.Files=hr;xt.FileBatches=ur;var xe,dr,at;class fr extends I{constructor(){super(...arguments),xe.add(this)}async unwrap(e,t,n=this._client.webhookSecret,r=300){return await this.verifySignature(e,t,n,r),JSON.parse(e)}async verifySignature(e,t,n=this._client.webhookSecret,r=300){if(typeof crypto>"u"||typeof crypto.subtle.importKey!="function"||typeof crypto.subtle.verify!="function")throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");c(this,xe,"m",dr).call(this,n);const a=S([t]).values,i=c(this,xe,"m",at).call(this,a,"webhook-signature"),o=c(this,xe,"m",at).call(this,a,"webhook-timestamp"),l=c(this,xe,"m",at).call(this,a,"webhook-id"),u=parseInt(o,10);if(isNaN(u))throw new Re("Invalid webhook timestamp format");const m=Math.floor(Date.now()/1e3);if(m-u>r)throw new Re("Webhook timestamp is too old");if(u>m+r)throw new Re("Webhook timestamp is too new");const h=i.split(" ").map(w=>w.startsWith("v1,")?w.substring(3):w),g=n.startsWith("whsec_")?Buffer.from(n.replace("whsec_",""),"base64"):Buffer.from(n,"utf-8"),d=l?`${l}.${o}.${e}`:`${o}.${e}`,b=await crypto.subtle.importKey("raw",g,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(const w of h)try{const v=Buffer.from(w,"base64");if(await crypto.subtle.verify("HMAC",b,v,new TextEncoder().encode(d)))return}catch{continue}throw new Re("The given webhook signature does not match the expected signature")}}xe=new WeakSet,dr=function(e){if(typeof e!="string"||e.length===0)throw new Error("The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function")},at=function(e,t){if(!e)throw new Error("Headers are required");const n=e.get(t);if(n==null)throw new Error(`Missing required header: ${t}`);return n};var qt,mn,it,mr;class O{constructor({baseURL:e=ge("OPENAI_BASE_URL"),apiKey:t=ge("OPENAI_API_KEY"),organization:n=ge("OPENAI_ORG_ID")??null,project:r=ge("OPENAI_PROJECT_ID")??null,webhookSecret:a=ge("OPENAI_WEBHOOK_SECRET")??null,...i}={}){if(qt.add(this),it.set(this,void 0),this.completions=new Xs(this),this.chat=new Yt(this),this.embeddings=new Gs(this),this.files=new zs(this),this.images=new sr(this),this.audio=new Ue(this),this.moderations=new ar(this),this.models=new rr(this),this.fineTuning=new Ae(this),this.graders=new ln(this),this.vectorStores=new xt(this),this.webhooks=new fr(this),this.beta=new qe(this),this.batches=new Bs(this),this.uploads=new fn(this),this.responses=new dn(this),this.realtime=new un(this),this.conversations=new nn(this),this.evals=new rn(this),this.containers=new tn(this),t===void 0)throw new x("Missing credentials. Please pass an `apiKey`, or set the `OPENAI_API_KEY` environment variable.");const o={apiKey:t,organization:n,project:r,webhookSecret:a,...i,baseURL:e||"https://api.openai.com/v1"};if(!o.dangerouslyAllowBrowser&&kr())throw new x(`It looks like you're running in a browser-like environment.
|
|
15
|
+
|
|
16
|
+
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
17
|
+
If you understand the risks and have appropriate mitigations in place,
|
|
18
|
+
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
19
|
+
|
|
20
|
+
new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
|
|
21
|
+
|
|
22
|
+
https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
|
|
23
|
+
`);this.baseURL=o.baseURL,this.timeout=o.timeout??mn.DEFAULT_TIMEOUT,this.logger=o.logger??console;const l="warn";this.logLevel=l,this.logLevel=In(o.logLevel,"ClientOptions.logLevel",this)??In(ge("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??l,this.fetchOptions=o.fetchOptions,this.maxRetries=o.maxRetries??2,this.fetch=o.fetch??Mr(),R(this,it,jr),this._options=o,this.apiKey=typeof t=="string"?t:"Missing Key",this.organization=n,this.project=r,this.webhookSecret=a}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){}async authHeaders(e){return S([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return Ur(e,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${we}`}defaultIdempotencyKey(){return`stainless-node-retry-${qn()}`}makeStatusError(e,t,n,r){return H.generate(e,t,n,r)}async _callApiKey(){const e=this._options.apiKey;if(typeof e!="function")return!1;let t;try{t=await e()}catch(n){throw n instanceof x?n:new x(`Failed to get token from 'apiKey' function: ${n.message}`,{cause:n})}if(typeof t!="string"||!t)throw new x(`Expected 'apiKey' function argument to return a string but it returned ${t}`);return this.apiKey=t,!0}buildURL(e,t,n){const r=!c(this,qt,"m",mr).call(this)&&n||this.baseURL,a=vr(e)?new URL(e):new URL(r+(r.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),i=this.defaultQuery();return Cr(i)||(t={...i,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(a.search=this.stringifyQuery(t)),a.toString()}async prepareOptions(e){await this._callApiKey()}async prepareRequest(e,{url:t,options:n}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,n){return this.request(Promise.resolve(n).then(r=>({method:e,path:t,...r})))}request(e,t=null){return new _t(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,n){var E,p;const r=await e,a=r.maxRetries??this.maxRetries;t==null&&(t=a),await this.prepareOptions(r);const{req:i,url:o,timeout:l}=await this.buildRequest(r,{retryCount:a-t});await this.prepareRequest(i,{url:o,options:r});const u="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),m=n===void 0?"":`, retryOf: ${n}`,h=Date.now();if(q(this).debug(`[${u}] sending request`,le({retryOfRequestLogID:n,method:r.method,url:o,options:r,headers:i.headers})),(E=r.signal)!=null&&E.aborted)throw new z;const g=new AbortController,d=await this.fetchWithTimeout(o,i,l,g).catch(Pt),b=Date.now();if(d instanceof globalThis.Error){const y=`retrying, ${t} attempts remaining`;if((p=r.signal)!=null&&p.aborted)throw new z;const _=Et(d)||/timed? ?out/i.test(String(d)+("cause"in d?String(d.cause):""));if(t)return q(this).info(`[${u}] connection ${_?"timed out":"failed"} - ${y}`),q(this).debug(`[${u}] connection ${_?"timed out":"failed"} (${y})`,le({retryOfRequestLogID:n,url:o,durationMs:b-h,message:d.message})),this.retryRequest(r,t,n??u);throw q(this).info(`[${u}] connection ${_?"timed out":"failed"} - error; no more retries left`),q(this).debug(`[${u}] connection ${_?"timed out":"failed"} (error; no more retries left)`,le({retryOfRequestLogID:n,url:o,durationMs:b-h,message:d.message})),_?new Jt:new pt({cause:d})}const w=[...d.headers.entries()].filter(([y])=>y==="x-request-id").map(([y,_])=>", "+y+": "+JSON.stringify(_)).join(""),v=`[${u}${m}${w}] ${i.method} ${o} ${d.ok?"succeeded":"failed"} with status ${d.status} in ${b-h}ms`;if(!d.ok){const y=await this.shouldRetry(d);if(t&&y){const A=`retrying, ${t} attempts remaining`;return await Nr(d.body),q(this).info(`${v} - ${A}`),q(this).debug(`[${u}] response error (${A})`,le({retryOfRequestLogID:n,url:d.url,status:d.status,headers:d.headers,durationMs:b-h})),this.retryRequest(r,t,n??u,d.headers)}const _=y?"error; no more retries left":"error; not retryable";q(this).info(`${v} - ${_}`);const C=await d.text().catch(A=>Pt(A).message),k=$r(C),$=k?void 0:C;throw q(this).debug(`[${u}] response error (${_})`,le({retryOfRequestLogID:n,url:d.url,status:d.status,headers:d.headers,message:$,durationMs:Date.now()-h})),this.makeStatusError(d.status,k,$,d.headers)}return q(this).info(v),q(this).debug(`[${u}] response start`,le({retryOfRequestLogID:n,url:d.url,status:d.status,headers:d.headers,durationMs:b-h})),{response:d,options:r,controller:g,requestLogID:u,retryOfRequestLogID:n,startTime:h}}getAPIList(e,t,n){return this.requestAPIList(t,{method:"get",path:e,...n})}requestAPIList(e,t){const n=this.makeRequest(t,null,void 0);return new zr(this,n,e)}async fetchWithTimeout(e,t,n,r){const{signal:a,method:i,...o}=t||{};a&&a.addEventListener("abort",()=>r.abort());const l=setTimeout(()=>r.abort(),n),u=globalThis.ReadableStream&&o.body instanceof globalThis.ReadableStream||typeof o.body=="object"&&o.body!==null&&Symbol.asyncIterator in o.body,m={signal:r.signal,...u?{duplex:"half"}:{},method:"GET",...o};i&&(m.method=i.toUpperCase());try{return await this.fetch.call(void 0,e,m)}finally{clearTimeout(l)}}async shouldRetry(e){const t=e.headers.get("x-should-retry");return t==="true"?!0:t==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,n,r){let a;const i=r==null?void 0:r.get("retry-after-ms");if(i){const l=parseFloat(i);Number.isNaN(l)||(a=l)}const o=r==null?void 0:r.get("retry-after");if(o&&!a){const l=parseFloat(o);Number.isNaN(l)?a=Date.parse(o)-Date.now():a=l*1e3}if(!(a&&0<=a&&a<60*1e3)){const l=e.maxRetries??this.maxRetries;a=this.calculateDefaultRetryTimeoutMillis(t,l)}return await Be(a),this.makeRequest(e,t-1,n)}calculateDefaultRetryTimeoutMillis(e,t){const a=t-e,i=Math.min(.5*Math.pow(2,a),8),o=1-Math.random()*.25;return i*o*1e3}async buildRequest(e,{retryCount:t=0}={}){const n={...e},{method:r,path:a,query:i,defaultBaseURL:o}=n,l=this.buildURL(a,i,o);"timeout"in n&&Rr("timeout",n.timeout),n.timeout=n.timeout??this.timeout;const{bodyHeaders:u,body:m}=this.buildBody({options:n}),h=await this.buildHeaders({options:e,method:r,bodyHeaders:u,retryCount:t});return{req:{method:r,headers:h,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&m instanceof globalThis.ReadableStream&&{duplex:"half"},...m&&{body:m},...this.fetchOptions??{},...n.fetchOptions??{}},url:l,timeout:n.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:n,retryCount:r}){let a={};this.idempotencyHeader&&t!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),a[this.idempotencyHeader]=e.idempotencyKey);const i=S([a,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(r),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...Tr(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(i),i.values}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};const n=S([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&n.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:ns(e)}:c(this,it,"f").call(this,{body:e,headers:n})}}mn=O,it=new WeakMap,qt=new WeakSet,mr=function(){return this.baseURL!=="https://api.openai.com/v1"};O.OpenAI=mn;O.DEFAULT_TIMEOUT=6e5;O.OpenAIError=x;O.APIError=H;O.APIConnectionError=pt;O.APIConnectionTimeoutError=Jt;O.APIUserAbortError=z;O.NotFoundError=Kn;O.ConflictError=Vn;O.RateLimitError=Qn;O.BadRequestError=Jn;O.AuthenticationError=Hn;O.InternalServerError=zn;O.PermissionDeniedError=Xn;O.UnprocessableEntityError=Gn;O.InvalidWebhookSignatureError=Re;O.toFile=ra;O.Completions=Xs;O.Chat=Yt;O.Embeddings=Gs;O.Files=zs;O.Images=sr;O.Audio=Ue;O.Moderations=ar;O.Models=rr;O.FineTuning=Ae;O.Graders=ln;O.VectorStores=xt;O.Webhooks=fr;O.Beta=qe;O.Batches=Bs;O.Uploads=fn;O.Responses=dn;O.Realtime=un;O.Conversations=nn;O.Evals=rn;O.Containers=tn;const Oa=yr(()=>import("./docs-BrInh2Pn.js"),[],import.meta.url);let ze=null;async function Ea(s){if(ze)return ze;const e=await s.getObjectViewSystem("state","","香"),t=await s.getObjectViewSystem("channel","","香"),n=await s.getObjectViewSystem("device","","香"),r=await s.getObjectViewSystem("folder","","香"),a=await s.getObjectViewSystem("enum","","香");return ze=Object.assign(e,t,n,r,a),ze}function ye(s,e){return s&&typeof s=="object"?s[e]||s.en:s||""}async function Pa(s){var b,w,v,E;const e=U.I18n.getLanguage(),t=await Ea(s),n=Object.keys(t).sort(),r=new wr,a=[],i=["UNREACH_STICKY"],o=[br.Types.info],l=[],u=[],m=[],h=[];n.forEach(p=>{var y,_,C;((y=t[p])==null?void 0:y.type)==="enum"?l.push(p):(C=(_=t[p])==null?void 0:_.common)!=null&&C.smartName&&h.push(p)}),l.forEach(p=>{p.startsWith("enum.rooms.")?u.push(p):p.startsWith("enum.functions.")&&m.push(p);const y=t[p].common.members;y!=null&&y.length&&y.forEach(_=>{t[_]&&(h.includes(_)||h.push(_))})});const g={id:"",objects:t,_keysOptional:n,_usedIdsOptional:a,ignoreIndicators:i,excludedTypes:o},d=[];h.forEach(p=>{g.id=p;const y=r.detect(g);y&&y.forEach(_=>{var me;const C=(me=_.states.find(N=>N.id))==null?void 0:me.id;if(!C||d.find(N=>N.id===C))return;const k=t[C],$={id:C,name:ye(k.common.name,e),type:k.type,deviceType:_.type,states:_.states.filter(N=>N.id).map(N=>({id:N.id,name:N.name,role:N.defaultRole,type:t[N.id].common.type,unit:t[N.id].common.unit,read:t[N.id].common.read===void 0?!0:t[N.id].common.read,write:t[N.id].common.write===void 0?!0:t[N.id].common.write}))},F=C.split(".");let A,T;(k.type==="channel"||k.type==="state")&&(F.pop(),A=F.join("."),t[A]&&(t[A].type==="channel"||t[A].type==="folder")?(F.pop(),T=F.join("."),(!t[T]||t[T].type!=="device"&&t[A].type!=="folder")&&(T=void 0)):A=void 0);const M=u.find(N=>{var ie,ve,Ce;return(ie=t[N].common.members)!=null&&ie.includes(C)||A&&((ve=t[N].common.members)!=null&&ve.includes(A))?!0:T&&((Ce=t[N].common.members)==null?void 0:Ce.includes(T))});M&&($.room=ye(t[M].common.name,e));const se=m.find(N=>{var ie,ve,Ce;return(ie=t[N].common.members)!=null&&ie.includes(C)||A&&((ve=t[N].common.members)!=null&&ve.includes(A))?!0:T&&((Ce=t[N].common.members)==null?void 0:Ce.includes(T))});se&&($.function=ye(t[se].common.name,e)),d.push($)})});for(let p=0;p<d.length;p++){const y=d[p];if(y.type==="state"||y.type==="channel"){const _=y.id.split(".");_.pop();const C=t[_.join(".")];if(C&&(C.type==="channel"||C.type==="device"||C.type==="folder")){y.name=ye(((b=C.common)==null?void 0:b.name)||y.name,e),_.pop();const k=t[_.join(".")];(k==null?void 0:k.type)==="device"&&((w=k.common)!=null&&w.icon)&&(y.name=ye(((v=k.common)==null?void 0:v.name)||y.name,e))}else y.name=ye(((E=C==null?void 0:C.common)==null?void 0:E.name)||y.name,e)}}return d}const Ta=async()=>(await Oa).default,Ma={ru:"Russian",en:"English",de:"German",es:"Spanish",fr:"French",it:"Italian",pl:"Polish",nl:"Dutch",pt:"Portuguese",uk:"Ukrainian","zh-cn":"Chinese"},Za=s=>{const[e,t]=Z.useState(window.localStorage.getItem("openai-question")||""),[n,r]=Z.useState(""),[a,i]=Z.useState(!1),[o,l]=Z.useState(!1),[u,m]=Z.useState(window.localStorage.getItem("openai-model")||"gpt-4o"),[h,g]=Z.useState(!1),d=Z.useRef(null),b=Z.useRef(null),w=Z.useRef(null),v=Z.useCallback(async()=>{var _;let E;d.current?E=d.current:(E=await Pa(s.socket),d.current=E,console.log(`devices: ${JSON.stringify(E,null,2)}`));let p;if(b.current)p=b.current;else{const C=Object.keys(s.runningInstances);for(let k=0;k<C.length;k++){const $=await s.socket.getObject(C[k]);if(p=(($==null?void 0:$.native.gptKey)||"").trim(),p)break}b.current=p||null}let y;if(w.current?y=w.current:(y=await Ta(),w.current=y),!p){g(!0);return}i(!0),l(!1);try{const $=(await new O({apiKey:p,dangerouslyAllowBrowser:!0}).chat.completions.create({model:u,messages:[{role:"system",content:`You are programmer. Here is a documentation:
|
|
24
|
+
|
|
25
|
+
${y}`},{role:"system",content:`Here is list of devices:
|
|
26
|
+
|
|
27
|
+
${JSON.stringify(E,null,2)}`},{role:"user",content:`Write JavaScript code that does:
|
|
28
|
+
|
|
29
|
+
${e}
|
|
30
|
+
Return only code.
|
|
31
|
+
Write comments in ${Ma[U.I18n.getLanguage()]||"English"}.
|
|
32
|
+
You can call async function directly in the code without encapsulate them in async function as this code will be already executed in async function.
|
|
33
|
+
Do not import any libraries as all functions are already imported.`}]})).choices[0].message,F=(_=$.content)==null?void 0:_.match(/```(javascript|js|typescript)\n?(.*)```(.*)/ms);let A;if(!F)A=$.content,A!=null&&A.startsWith("`")&&(A=A.substring(1)),A!=null&&A.endsWith("`")&&(A=A.substring(0,A.length-1));else if(A=F[2],F[3]){const T=F[3].split(`
|
|
34
|
+
`).map(M=>M.trim());for(;T[0]==="";)T.shift();A=`${T.map(M=>`// ${M}`).join(`
|
|
35
|
+
`)}
|
|
36
|
+
${A}`}console.log($),r(A||"")}catch(C){console.log(JSON.stringify(C)),C.error&&l(C.error.message),console.error(`Cannot request: ${C}, ${JSON.stringify(C.error||C,null,2)}`)}i(!1)},[e,u,s.runningInstances,s.socket]);return P.jsxs(j.Dialog,{maxWidth:"lg",sx:{"& .MuiDialog-paper":{height:"calc(100% - 100px)"}},open:!0,onClose:()=>s.onClose(),fullWidth:!0,children:[h&&P.jsxs(j.Dialog,{maxWidth:"lg",open:!0,onClose:()=>g(!1),fullWidth:!0,children:[P.jsx(j.DialogTitle,{children:U.I18n.t("No Chat GPT Key found")}),P.jsxs(j.DialogContent,{style:{display:"flex",flexDirection:"column",gap:8},children:[P.jsx("div",{children:U.I18n.t("You have to enter OpenAI API key in the configuration of javascript adapter.")}),P.jsx(j.Button,{variant:"contained",onClick:()=>{const E=Object.keys(s.runningInstances);window.open(`../../#tab-instances/config/${E[0]||"system.adapter.javascript.0"}`,"_blank"),g(!1)},children:U.I18n.t("Open configuration")})]}),P.jsx(j.DialogActions,{children:P.jsx(j.Button,{variant:"contained",startIcon:P.jsx(pn,{}),onClick:()=>g(!1),children:U.I18n.t("Close")})})]}),P.jsx(j.DialogTitle,{children:U.I18n.t("AI code generator")}),P.jsxs(j.DialogContent,{style:{display:"flex",flexDirection:"column",gap:8,height:"100%"},children:[P.jsx("div",{children:P.jsx(j.TextField,{variant:"standard",multiline:!0,autoFocus:!0,disabled:a,fullWidth:!0,onKeyUp:E=>{E.key==="Enter"&&E.ctrlKey&&v()},label:U.I18n.t("Enter your question"),helperText:U.I18n.t("Press Ctrl+Enter to get the answer"),value:e,onChange:E=>{window.localStorage.setItem("openai-question",E.target.value),t(E.target.value)}})}),P.jsxs("div",{style:{display:"flex",alignItems:"baseline"},children:[P.jsx(j.Button,{variant:"contained",disabled:a||!e,startIcon:P.jsx(Sr,{}),onClick:async()=>v(),children:a?P.jsx(j.CircularProgress,{size:24}):U.I18n.t("Ask")}),P.jsxs(j.FormControl,{style:{width:150,marginLeft:20},variant:"standard",children:[P.jsx(j.InputLabel,{children:U.I18n.t("Model")}),P.jsxs(j.Select,{variant:"standard",value:u,onChange:E=>{window.localStorage.setItem("openai-model",E.target.value),o&&l(!1),m(E.target.value)},children:[P.jsx(j.MenuItem,{value:"gpt-4o",children:"GPT-4o"}),P.jsx(j.MenuItem,{value:"gpt-4-turbo",children:"GPT-4 Turbo"}),P.jsx(j.MenuItem,{value:"gpt-4-32k",children:"GPT-4 32k"}),P.jsx(j.MenuItem,{value:"gpt-4",children:"GPT-4"}),P.jsx(j.MenuItem,{value:"gpt-3.5-turbo-16k",children:"GPT-3.5 Turbo"})]})]})]}),P.jsx("div",{children:U.I18n.t("Result")}),P.jsx("div",{style:{height:"calc(100% - 155px)"},children:o?P.jsx("div",{style:{color:s.themeType==="dark"?"#984242":"#bb0000"},children:o}):P.jsx(xr,{triggerPrettier:1,adapterName:s.adapterName,runningInstances:s.runningInstances,style:{height:"100%",width:"100%",resize:"none"},name:"ai",socket:s.socket,readOnly:!0,checkJs:!0,code:n,isDark:s.themeType==="dark",language:s.language||"javascript"})})]}),P.jsxs(j.DialogActions,{children:[P.jsx(j.Button,{color:"grey",variant:"outlined",disabled:!n,startIcon:P.jsx(_r,{}),onClick:()=>{U.Utils.copyToClipboard(n),window.alert(U.I18n.t("Copied"))},children:U.I18n.t("Copy to clipboard")}),P.jsx(j.Button,{color:"primary",variant:"contained",disabled:!n||o,startIcon:P.jsx(gr,{}),onClick:()=>{s.onAddCode(n),s.onClose()},children:U.I18n.t("Use generated code")}),P.jsx(j.Button,{color:"grey",variant:"contained",startIcon:P.jsx(pn,{}),onClick:()=>s.onClose(),children:U.I18n.t("Close")})]})]})};export{Za as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{c,j as s}from"./createSvgIcon-
|
|
1
|
+
import{c,j as s}from"./createSvgIcon-DlIk-fDn.js";const o=c(s.jsx("path",{d:"M17 3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V7zm-5 16c-1.66 0-3-1.34-3-3s1.34-3 3-3 3 1.34 3 3-1.34 3-3 3m3-10H5V5h10z"}),"Save");export{o as I};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{j as e}from"./createSvgIcon-
|
|
1
|
+
import{j as e}from"./createSvgIcon-DlIk-fDn.js";import{R as i}from"./iobroker_javascript__loadShare__react__loadShare__-i8pXne9X.js";import{i as r,I as n}from"./index-Cjl4b70e.js";import{i as a}from"./index-CePzv5-W.js";import l from"./ScriptEditorVanillaMonaco-Xge2wqgO.js";import{I as c}from"./Save-DXaUpIPM.js";import"./_commonjsHelpers-Cpj98o6Y.js";import"./iobroker_javascript__mf_v__runtimeInit__mf_v__-DZdFIfoQ.js";import"./inheritsLoose-DNrhibGS.js";import"./preload-helper-BDBacUwf.js";const o={textArea:{width:"calc(100% - 10px)",resize:"none"},dialog:{height:"95%"},fullHeight:{height:"100%",overflow:"hidden"},args:s=>({color:s.palette.mode==="dark"?"white":"black",height:30,width:"100%",fontSize:16}),argsTitle:s=>({color:s.palette.mode==="dark"?"white":"black",fontWeight:"bold"})};class k extends i.Component{constructor(t){super(t),this.state={changed:!1,source:!t.source&&t.isReturn?`
|
|
2
2
|
return false`:t.source}}componentDidMount(){setTimeout(()=>{var t;try{(t=window.document.getElementById("source-text-area"))==null||t.focus()}catch{}},100)}handleCancel(){this.props.onClose(!1)}handleOk(){(!this.props.isReturn||this.state.source.includes("return "))&&this.props.onClose(this.state.source)}onChange(t){this.setState({changed:!0,source:t})}render(){return e.jsxs(r.Dialog,{onClose:()=>!1,maxWidth:"lg",sx:{"& .MuiDialog-paper":o.dialog},fullWidth:!0,open:!0,"aria-labelledby":"source-dialog-title",children:[e.jsx(r.DialogTitle,{id:"source-dialog-title",children:a.I18n.t("Function editor")}),e.jsxs(r.DialogContent,{style:o.fullHeight,children:[this.props.args&&e.jsxs(r.Box,{sx:o.args,children:[e.jsx(r.Box,{component:"span",sx:o.argsTitle,children:a.I18n.t("function (")}),this.props.args,e.jsx(r.Box,{component:"span",sx:o.argsTitle,children:")"})]},"arguments"),e.jsx(l,{triggerPrettier:1,adapterName:this.props.adapterName,runningInstances:this.props.runningInstances,style:{...o.textArea,height:this.props.args?"calc(100% - 30px)":"100%"},name:"blockly",socket:this.props.socket,readOnly:!1,checkJs:!1,changed:this.state.changed,code:this.state.source,isDark:this.props.themeType==="dark",onChange:t=>this.onChange(t),language:"javascript"},"scriptEditor")]}),e.jsxs(r.DialogActions,{children:[e.jsx(r.Button,{variant:"contained",onClick:()=>this.handleOk(),color:"primary",startIcon:e.jsx(c,{}),children:a.I18n.t("Save")}),e.jsx(r.Button,{color:"grey",variant:"contained",onClick:()=>this.handleCancel(),startIcon:e.jsx(n,{}),children:a.I18n.t("Cancel")})]})]})}}export{k as default};
|
package/admin/assets/{ScriptEditorVanillaMonaco-BWe9MiKn.js → ScriptEditorVanillaMonaco-Xge2wqgO.js}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{j as n}from"./createSvgIcon-C_ElRFrf.js";import{R as S}from"./iobroker_javascript__loadShare__react__loadShare__-B-pIv4x_.js";import{i as p,o as b,av as C}from"./index-DeFm7TiX.js";import{i as f}from"./index-BUU5hWiL.js";import"./_commonjsHelpers-Cpj98o6Y.js";import"./iobroker_javascript__mf_v__runtimeInit__mf_v__-CmuPLb0X.js";import"./inheritsLoose-CLw44UEv.js";import"./preload-helper-Dp1pzeXC.js";function v(w){return/^script\.js\.global\./.test(w)}let O=0;function E(w){const t=/\x1b\[[0-9;]*m/g;return w.replace(t,"")}class R extends S.Component{monacoDiv=null;editor=null;monaco=window.monaco;insert="";originalCode;runningInstancesStr;monacoCounter=0;location;breakpoints;lastSearch="";typings={};decorations=[];triggerPrettier;constructor(t){super(t),this.state={name:"current",isDark:t.isDark||!1,language:t.language||"javascript",readOnly:t.readOnly||!1,alive:!0,check:!1,searchText:this.props.searchText||"",typingsLoaded:!1,showError:null},this.triggerPrettier=t.triggerPrettier,this.runningInstancesStr=JSON.stringify(this.props.runningInstances),this.originalCode=t.code||"",this.monacoDiv=S.createRef()}waitForMonaco(t){var e,s,o,r,l,a,h,g;let i=!!((r=(o=(s=(e=this.monaco)==null?void 0:e.languages)==null?void 0:s.typescript)==null?void 0:o.typescriptDefaults)!=null&&r.getCompilerOptions);if(!i||!this.props.runningInstances){if(this.monaco=window.monaco,i=!!((g=(h=(a=(l=this.monaco)==null?void 0:l.languages)==null?void 0:a.typescript)==null?void 0:h.typescriptDefaults)!=null&&g.getCompilerOptions),this.monacoCounter++,!i&&this.monacoCounter<20){console.log("wait for monaco loaded"),setTimeout(()=>this.waitForMonaco(t),200);return}this.monacoCounter>=20&&console.error("Cannot load monaco!")}else t&&t()}loadTypings(t){if(!this.editor)return;t||=this.props.runningInstances;const i=t&&Object.keys(t).find(e=>t==null?void 0:t[e]);i&&this.props.socket.sendTo(i.replace("system.adapter.",""),"loadTypings",null).then(e=>{this.setState({alive:!0,check:!0,typingsLoaded:!0}),this.setTypeCheck(!0),e.typings?(this.typings=e.typings,this.setEditorTypings(this.state.name)):console.error(`failed to load typings: ${e.error}`)})}componentDidMount(){var e,s,o,r,l,a,h,g,y,k,d,u;let t=!!((r=(o=(s=(e=this.monaco)==null?void 0:e.languages)==null?void 0:s.typescript)==null?void 0:o.typescriptDefaults)!=null&&r.getCompilerOptions);if((!t||!this.props.runningInstances)&&(this.monaco=window.monaco,t=!!((g=(h=(a=(l=this.monaco)==null?void 0:l.languages)==null?void 0:a.typescript)==null?void 0:h.typescriptDefaults)!=null&&g.getCompilerOptions),!t)){console.log("wait for monaco loaded..."),this.waitForMonaco(()=>this.componentDidMount());return}if(!this.editor&&t&&this.monaco){console.log("Init editor"),(k=(y=this.props).onRegisterSelect)==null||k.call(y,()=>{var m;if(this.editor){const D=this.editor.getSelection();if(D)return(m=this.editor.getModel())==null?void 0:m.getValueInRange(D)}});const c=this.monaco.languages.typescript.typescriptDefaults.getCompilerOptions();c.allowJs=!0,c.checkJs=this.props.checkJs!==!1,c.noLib=!0,c.lib=[],c.useUnknownInCatchVariables=!1,c.moduleResolution=this.monaco.languages.typescript.ModuleResolutionKind.NodeJs,c.target=this.monaco.languages.typescript.ScriptTarget.ESNext,c.module=this.monaco.languages.typescript.ModuleKind.ESNext,c.allowNonTsExtensions=!0,this.monaco.languages.typescript.typescriptDefaults.setCompilerOptions(c),this.setTypeCheck(!1),(d=this.monacoDiv)!=null&&d.current&&(this.editor=this.monaco.editor.create((u=this.monacoDiv)==null?void 0:u.current,{lineNumbers:"on",scrollBeyondLastLine:!1,automaticLayout:!0,glyphMargin:!!this.props.breakpoints,colorDecorators:!0}),this.editor.onDidChangeModelContent(()=>this.onChange()),this.loadTypings(),this.props.onForceSave&&this.editor.addCommand(this.monaco.KeyMod.CtrlCmd|this.monaco.KeyCode.KeyS,()=>this.props.onForceSave&&this.props.onForceSave()),setTimeout(()=>{this.highlightText(this.state.searchText),this.location=this.props.location||void 0,this.breakpoints=this.props.breakpoints,this.showDecorators()}))}const i={selectOnLineNumbers:!0,scrollBeyondLastLine:!1,automaticLayout:!0,readOnly:this.state.readOnly,language:this.state.language,isDark:this.state.isDark};this.setEditorOptions(i),this.editor&&(this.editor.focus(),this.editor.setValue(this.originalCode),this.props.onToggleBreakpoint?this.editor.onMouseDown(c=>{var D;const m=c.target;this.props.onToggleBreakpoint&&((D=m.detail)==null?void 0:D.glyphMarginLeft)!==void 0&&m.position&&this.props.onToggleBreakpoint(m.position.lineNumber-1)}):this.editor.onMouseDown(()=>{}))}setEditorOptions(t){var i;t&&(t.language&&this.setEditorLanguage(t.language),this.editor&&(t.readOnly!==void 0&&this.editor.updateOptions({readOnly:t.readOnly}),t.lineWrap!==void 0&&this.editor.updateOptions({wordWrap:t.lineWrap?"on":"off"})),t.typeCheck!==void 0&&this.setTypeCheck(t.typeCheck),t.isDark!==void 0&&((i=this.monaco)==null||i.editor.setTheme(t.isDark?"vs-dark":"vs")))}componentWillUnmount(){var t,i;this.editor&&((i=(t=this.props).onRegisterSelect)==null||i.call(t,null),this.editor.dispose(),this.editor=null)}async doPrettier(){var e,s,o,r;const t=this.props.runningInstances&&Object.keys(this.props.runningInstances).find(l=>{var a;return(a=this.props.runningInstances)==null?void 0:a[l]});if(!t){window.alert(f.I18n.t("No script adapter instance found to format the code"));return}const i=await this.props.socket.sendTo(t.replace("system.adapter.",""),"prettier",{code:(e=this.editor)==null?void 0:e.getValue(),type:this.state.language});i.error?this.setState({showError:{title:f.I18n.t("Error formatting code"),message:E(i.error)}}):i.code&&((s=this.editor)==null||s.setValue(i.code),(r=(o=this.props).onChange)==null||r.call(o,i.code),this.showDecorators())}setEditorLanguage(t){var e;if(!this.editor)return;const i=this.editor.getModel();if(i){const s=i.getValue(),o=i.uri.path,r=typeof o=="string"&&o.includes(".")?o.substring(0,o.lastIndexOf(".")):"index",l=t==="javascript"?"js":t==="typescript"?"ts":t;i.dispose();const a=t==="javascript"||t==="typescript"?"typescript":t,h=(e=this.monaco)==null?void 0:e.editor.createModel(s,a,this.monaco.Uri.from({scheme:window.location.protocol.replace(":",""),path:`${r}${O++}.${l}`}));h&&this.editor.setModel(h)}}setTypeCheck(t){var e,s;const i={noSemanticValidation:!this.state.alive||!t,noSyntaxValidation:!this.state.alive};(e=this.monaco)==null||e.languages.typescript.typescriptDefaults.setDiagnosticsOptions(i),(s=this.monaco)==null||s.languages.typescript.javascriptDefaults.setDiagnosticsOptions({noSemanticValidation:!this.state.alive||!t,noSyntaxValidation:!this.state.alive})}setEditorTypings(t=""){var o,r,l,a,h,g,y,k;const i=v(t),e=`${t}.d.ts`,s=[];for(const d of Object.keys(this.typings))i&&(d==="global.d.ts"||d.startsWith("script.js.global")&&d!==e)||s.push({filePath:d,content:this.typings[d]});if((a=(l=(r=(o=this.monaco)==null?void 0:o.languages)==null?void 0:r.typescript)==null?void 0:l.typescriptDefaults)!=null&&a.setExtraLibs)this.monaco.languages.typescript.typescriptDefaults.setExtraLibs(s);else if((k=(y=(g=(h=this.monaco)==null?void 0:h.languages)==null?void 0:g.typescript)==null?void 0:y.typescriptDefaults)!=null&&k.addExtraLib){const d=this.monaco.languages.typescript.typescriptDefaults.getExtraLibs();s.forEach(u=>{!d[u.filePath]&&this.monaco&&this.monaco.languages.typescript.typescriptDefaults.addExtraLib(u.content,u.filePath)})}}insertTextIntoEditor(t){if(!this.editor||!this.monaco)return;const i=this.editor.getSelection();if(i){const e=new this.monaco.Range(i.startLineNumber,i.startColumn,i.endLineNumber,i.endColumn);this.editor.executeEdits("",[{range:e,text:t,forceMoveMarkers:!0}])}this.editor.focus()}highlightText(t){var e;if(!this.editor||!this.monaco)return;const i=t?(e=this.editor.getModel())==null?void 0:e.findMatches(t,!0,!1,!1,null,!0):void 0;if(i!=null&&i.length)i.forEach(s=>{var o;return(o=this.editor)==null?void 0:o.setSelection(s.range)}),this.editor.revealLine(i[0].range.startLineNumber);else{const s=this.editor.getPosition();if(s){const o=s.lineNumber,r=s.column;this.editor.setSelection(new this.monaco.Range(o,r,o,r))}}}showDecorators(){var i;const t=[];if(this.location&&this.monaco&&(t.push({range:new this.monaco.Range(this.location.lineNumber+1,(this.location.columnNumber||0)+1,this.location.lineNumber+1,1e3),options:{isWholeLine:!1,className:this.props.isDark?"monacoCurrentLineDark":"monacoCurrentLine"}}),t.push({range:new this.monaco.Range(this.location.lineNumber+1,0,this.location.lineNumber+1,0),options:{isWholeLine:!0,className:this.props.isDark?"monacoCurrentFullLineDark":"monacoCurrentFullLine"}})),(i=this.breakpoints)==null||i.forEach(e=>{this.monaco&&t.push({range:new this.monaco.Range(e.location.lineNumber+1,0,e.location.lineNumber+1,100),options:{isWholeLine:!0,glyphMarginClassName:this.props.isDark?"monacoBreakPointDark":"monacoBreakPoint"}})}),this.editor){const e=this.editor.getModel();e&&(this.decorations=e.deltaDecorations(this.decorations,t))}}initNewScript(t,i){var e;this.setState({name:t}),this.originalCode=i||"",(e=this.editor)==null||e.setValue(i||""),this.highlightText(this.lastSearch),this.showDecorators(),this.setEditorTypings(t)}scrollToLineIfNeeded(t){if(this.editor){const i=this.editor.getVisibleRanges();(!i||!i[0]||i[0].startLineNumber>t||t>i[0].endLineNumber)&&this.editor.revealLineInCenter(t)}}UNSAFE_componentWillReceiveProps(t){const i={};this.state.name!==t.name&&this.initNewScript(t.name,t.code),JSON.stringify(t.runningInstances)!==this.runningInstancesStr&&(this.runningInstancesStr=JSON.stringify(t.runningInstances),this.state.typingsLoaded||this.loadTypings(t.runningInstances)),this.editor&&!t.changed&&(t.code!==this.originalCode||t.code!==this.editor.getValue())&&(this.originalCode=t.code||"",this.editor.setValue(this.originalCode),this.showDecorators(),this.location&&this.scrollToLineIfNeeded(this.location.lineNumber+1)),t.searchText!==this.lastSearch&&(this.lastSearch=t.searchText||"",this.highlightText(this.lastSearch)),JSON.stringify(t.location)!==JSON.stringify(this.location)&&JSON.stringify(t.breakpoints)!==JSON.stringify(this.breakpoints)?(this.location=t.location||void 0,this.breakpoints=t.breakpoints,this.showDecorators(),this.editor&&this.location&&this.scrollToLineIfNeeded(this.location.lineNumber+1)):JSON.stringify(t.breakpoints)!==JSON.stringify(this.breakpoints)?(this.breakpoints=t.breakpoints,this.showDecorators()):JSON.stringify(t.location)!==JSON.stringify(this.location)&&(this.location=t.location||void 0,this.showDecorators(),this.editor&&this.location&&this.scrollToLineIfNeeded(this.location.lineNumber+1)),this.state.language!==(t.language||"javascript")?(this.setState({language:t.language||"javascript"}),i.language=t.language||"javascript"):this.state.readOnly!==(t.readOnly||!1)?(this.setState({readOnly:t.readOnly||!1}),i.readOnly=t.readOnly):this.state.isDark!==(t.isDark||!1)&&(this.setState({isDark:t.isDark||!1}),i.isDark=t.isDark),this.setEditorOptions(i),this.insert!==t.insert&&(this.insert=t.insert||"",this.insert&&(console.log(`Insert text: ${this.insert}`),setTimeout(e=>{this.insertTextIntoEditor(e),setTimeout(()=>this.props.onInserted&&this.props.onInserted(),100)},100,this.insert)))}onChange(){var t,i;!this.props.readOnly&&this.editor&&((i=(t=this.props).onChange)==null||i.call(t,this.editor.getValue()))}renderErrorDialog(){return this.state.showError?this.state.showError.full?n.jsxs(p.Dialog,{open:!0,maxWidth:"md",onClose:()=>this.setState({showError:null}),children:[n.jsx(p.DialogTitle,{children:this.state.showError.title||f.I18n.t("Error")}),n.jsx(p.DialogContent,{children:n.jsx("pre",{children:n.jsx("code",{children:this.state.showError.message})})}),n.jsx(p.DialogActions,{children:n.jsxs(p.Button,{variant:"contained",startIcon:n.jsx(b,{}),onClick:()=>this.setState({showError:null}),children:[f.I18n.t("Close")," "]})})]}):n.jsx(p.Snackbar,{open:!0,autoHideDuration:5e3,onClose:()=>this.setState({showError:null}),message:this.state.showError.title,action:n.jsxs(S.Fragment,{children:[n.jsx(p.Button,{color:"secondary",size:"small",onClick:()=>this.setState({showError:{...this.state.showError,full:!0}}),children:f.I18n.t("More")}),n.jsx(p.IconButton,{size:"small","aria-label":"close",color:"inherit",onClick:()=>this.setState({showError:null}),children:n.jsx(b,{fontSize:"small"})})]})}):null}render(){var t,i,e;return!((e=(i=(t=this.monaco)==null?void 0:t.languages)==null?void 0:i.typescript)!=null&&e.typescriptDefaults)||!this.props.runningInstances?(setTimeout(()=>{this.monaco=window.monaco,this.forceUpdate()},200),null):(this.props.triggerPrettier!==this.triggerPrettier&&(this.triggerPrettier=this.props.triggerPrettier,setTimeout(()=>this.doPrettier().catch(s=>console.error("Error formatting code:",s)),50)),n.jsxs("div",{ref:this.monacoDiv,style:{...this.props.style,width:"100%",height:"100%",overflow:"hidden",position:"relative"},children:[this.renderErrorDialog(),!this.state.check&&n.jsx(p.Fab,{size:"small",title:f.I18n.t("Check is not active, because javascript adapter is disabled"),style:{bottom:10,right:10,opacity:.5,position:"absolute",zIndex:1,background:"red",color:"white"},color:"secondary",children:n.jsx(C,{})})]}))}}export{R as default};
|
|
1
|
+
import{j as n}from"./createSvgIcon-DlIk-fDn.js";import{R as S}from"./iobroker_javascript__loadShare__react__loadShare__-i8pXne9X.js";import{i as p,o as b,av as C}from"./index-Cjl4b70e.js";import{i as f}from"./index-CePzv5-W.js";import"./_commonjsHelpers-Cpj98o6Y.js";import"./iobroker_javascript__mf_v__runtimeInit__mf_v__-DZdFIfoQ.js";import"./inheritsLoose-DNrhibGS.js";import"./preload-helper-BDBacUwf.js";function v(w){return/^script\.js\.global\./.test(w)}let O=0;function E(w){const t=/\x1b\[[0-9;]*m/g;return w.replace(t,"")}class R extends S.Component{monacoDiv=null;editor=null;monaco=window.monaco;insert="";originalCode;runningInstancesStr;monacoCounter=0;location;breakpoints;lastSearch="";typings={};decorations=[];triggerPrettier;constructor(t){super(t),this.state={name:"current",isDark:t.isDark||!1,language:t.language||"javascript",readOnly:t.readOnly||!1,alive:!0,check:!1,searchText:this.props.searchText||"",typingsLoaded:!1,showError:null},this.triggerPrettier=t.triggerPrettier,this.runningInstancesStr=JSON.stringify(this.props.runningInstances),this.originalCode=t.code||"",this.monacoDiv=S.createRef()}waitForMonaco(t){var e,s,o,r,l,a,h,g;let i=!!((r=(o=(s=(e=this.monaco)==null?void 0:e.languages)==null?void 0:s.typescript)==null?void 0:o.typescriptDefaults)!=null&&r.getCompilerOptions);if(!i||!this.props.runningInstances){if(this.monaco=window.monaco,i=!!((g=(h=(a=(l=this.monaco)==null?void 0:l.languages)==null?void 0:a.typescript)==null?void 0:h.typescriptDefaults)!=null&&g.getCompilerOptions),this.monacoCounter++,!i&&this.monacoCounter<20){console.log("wait for monaco loaded"),setTimeout(()=>this.waitForMonaco(t),200);return}this.monacoCounter>=20&&console.error("Cannot load monaco!")}else t&&t()}loadTypings(t){if(!this.editor)return;t||=this.props.runningInstances;const i=t&&Object.keys(t).find(e=>t==null?void 0:t[e]);i&&this.props.socket.sendTo(i.replace("system.adapter.",""),"loadTypings",null).then(e=>{this.setState({alive:!0,check:!0,typingsLoaded:!0}),this.setTypeCheck(!0),e.typings?(this.typings=e.typings,this.setEditorTypings(this.state.name)):console.error(`failed to load typings: ${e.error}`)})}componentDidMount(){var e,s,o,r,l,a,h,g,y,k,d,u;let t=!!((r=(o=(s=(e=this.monaco)==null?void 0:e.languages)==null?void 0:s.typescript)==null?void 0:o.typescriptDefaults)!=null&&r.getCompilerOptions);if((!t||!this.props.runningInstances)&&(this.monaco=window.monaco,t=!!((g=(h=(a=(l=this.monaco)==null?void 0:l.languages)==null?void 0:a.typescript)==null?void 0:h.typescriptDefaults)!=null&&g.getCompilerOptions),!t)){console.log("wait for monaco loaded..."),this.waitForMonaco(()=>this.componentDidMount());return}if(!this.editor&&t&&this.monaco){console.log("Init editor"),(k=(y=this.props).onRegisterSelect)==null||k.call(y,()=>{var m;if(this.editor){const D=this.editor.getSelection();if(D)return(m=this.editor.getModel())==null?void 0:m.getValueInRange(D)}});const c=this.monaco.languages.typescript.typescriptDefaults.getCompilerOptions();c.allowJs=!0,c.checkJs=this.props.checkJs!==!1,c.noLib=!0,c.lib=[],c.useUnknownInCatchVariables=!1,c.moduleResolution=this.monaco.languages.typescript.ModuleResolutionKind.NodeJs,c.target=this.monaco.languages.typescript.ScriptTarget.ESNext,c.module=this.monaco.languages.typescript.ModuleKind.ESNext,c.allowNonTsExtensions=!0,this.monaco.languages.typescript.typescriptDefaults.setCompilerOptions(c),this.setTypeCheck(!1),(d=this.monacoDiv)!=null&&d.current&&(this.editor=this.monaco.editor.create((u=this.monacoDiv)==null?void 0:u.current,{lineNumbers:"on",scrollBeyondLastLine:!1,automaticLayout:!0,glyphMargin:!!this.props.breakpoints,colorDecorators:!0}),this.editor.onDidChangeModelContent(()=>this.onChange()),this.loadTypings(),this.props.onForceSave&&this.editor.addCommand(this.monaco.KeyMod.CtrlCmd|this.monaco.KeyCode.KeyS,()=>this.props.onForceSave&&this.props.onForceSave()),setTimeout(()=>{this.highlightText(this.state.searchText),this.location=this.props.location||void 0,this.breakpoints=this.props.breakpoints,this.showDecorators()}))}const i={selectOnLineNumbers:!0,scrollBeyondLastLine:!1,automaticLayout:!0,readOnly:this.state.readOnly,language:this.state.language,isDark:this.state.isDark};this.setEditorOptions(i),this.editor&&(this.editor.focus(),this.editor.setValue(this.originalCode),this.props.onToggleBreakpoint?this.editor.onMouseDown(c=>{var D;const m=c.target;this.props.onToggleBreakpoint&&((D=m.detail)==null?void 0:D.glyphMarginLeft)!==void 0&&m.position&&this.props.onToggleBreakpoint(m.position.lineNumber-1)}):this.editor.onMouseDown(()=>{}))}setEditorOptions(t){var i;t&&(t.language&&this.setEditorLanguage(t.language),this.editor&&(t.readOnly!==void 0&&this.editor.updateOptions({readOnly:t.readOnly}),t.lineWrap!==void 0&&this.editor.updateOptions({wordWrap:t.lineWrap?"on":"off"})),t.typeCheck!==void 0&&this.setTypeCheck(t.typeCheck),t.isDark!==void 0&&((i=this.monaco)==null||i.editor.setTheme(t.isDark?"vs-dark":"vs")))}componentWillUnmount(){var t,i;this.editor&&((i=(t=this.props).onRegisterSelect)==null||i.call(t,null),this.editor.dispose(),this.editor=null)}async doPrettier(){var e,s,o,r;const t=this.props.runningInstances&&Object.keys(this.props.runningInstances).find(l=>{var a;return(a=this.props.runningInstances)==null?void 0:a[l]});if(!t){window.alert(f.I18n.t("No script adapter instance found to format the code"));return}const i=await this.props.socket.sendTo(t.replace("system.adapter.",""),"prettier",{code:(e=this.editor)==null?void 0:e.getValue(),type:this.state.language});i.error?this.setState({showError:{title:f.I18n.t("Error formatting code"),message:E(i.error)}}):i.code&&((s=this.editor)==null||s.setValue(i.code),(r=(o=this.props).onChange)==null||r.call(o,i.code),this.showDecorators())}setEditorLanguage(t){var e;if(!this.editor)return;const i=this.editor.getModel();if(i){const s=i.getValue(),o=i.uri.path,r=typeof o=="string"&&o.includes(".")?o.substring(0,o.lastIndexOf(".")):"index",l=t==="javascript"?"js":t==="typescript"?"ts":t;i.dispose();const a=t==="javascript"||t==="typescript"?"typescript":t,h=(e=this.monaco)==null?void 0:e.editor.createModel(s,a,this.monaco.Uri.from({scheme:window.location.protocol.replace(":",""),path:`${r}${O++}.${l}`}));h&&this.editor.setModel(h)}}setTypeCheck(t){var e,s;const i={noSemanticValidation:!this.state.alive||!t,noSyntaxValidation:!this.state.alive};(e=this.monaco)==null||e.languages.typescript.typescriptDefaults.setDiagnosticsOptions(i),(s=this.monaco)==null||s.languages.typescript.javascriptDefaults.setDiagnosticsOptions({noSemanticValidation:!this.state.alive||!t,noSyntaxValidation:!this.state.alive})}setEditorTypings(t=""){var o,r,l,a,h,g,y,k;const i=v(t),e=`${t}.d.ts`,s=[];for(const d of Object.keys(this.typings))i&&(d==="global.d.ts"||d.startsWith("script.js.global")&&d!==e)||s.push({filePath:d,content:this.typings[d]});if((a=(l=(r=(o=this.monaco)==null?void 0:o.languages)==null?void 0:r.typescript)==null?void 0:l.typescriptDefaults)!=null&&a.setExtraLibs)this.monaco.languages.typescript.typescriptDefaults.setExtraLibs(s);else if((k=(y=(g=(h=this.monaco)==null?void 0:h.languages)==null?void 0:g.typescript)==null?void 0:y.typescriptDefaults)!=null&&k.addExtraLib){const d=this.monaco.languages.typescript.typescriptDefaults.getExtraLibs();s.forEach(u=>{!d[u.filePath]&&this.monaco&&this.monaco.languages.typescript.typescriptDefaults.addExtraLib(u.content,u.filePath)})}}insertTextIntoEditor(t){if(!this.editor||!this.monaco)return;const i=this.editor.getSelection();if(i){const e=new this.monaco.Range(i.startLineNumber,i.startColumn,i.endLineNumber,i.endColumn);this.editor.executeEdits("",[{range:e,text:t,forceMoveMarkers:!0}])}this.editor.focus()}highlightText(t){var e;if(!this.editor||!this.monaco)return;const i=t?(e=this.editor.getModel())==null?void 0:e.findMatches(t,!0,!1,!1,null,!0):void 0;if(i!=null&&i.length)i.forEach(s=>{var o;return(o=this.editor)==null?void 0:o.setSelection(s.range)}),this.editor.revealLine(i[0].range.startLineNumber);else{const s=this.editor.getPosition();if(s){const o=s.lineNumber,r=s.column;this.editor.setSelection(new this.monaco.Range(o,r,o,r))}}}showDecorators(){var i;const t=[];if(this.location&&this.monaco&&(t.push({range:new this.monaco.Range(this.location.lineNumber+1,(this.location.columnNumber||0)+1,this.location.lineNumber+1,1e3),options:{isWholeLine:!1,className:this.props.isDark?"monacoCurrentLineDark":"monacoCurrentLine"}}),t.push({range:new this.monaco.Range(this.location.lineNumber+1,0,this.location.lineNumber+1,0),options:{isWholeLine:!0,className:this.props.isDark?"monacoCurrentFullLineDark":"monacoCurrentFullLine"}})),(i=this.breakpoints)==null||i.forEach(e=>{this.monaco&&t.push({range:new this.monaco.Range(e.location.lineNumber+1,0,e.location.lineNumber+1,100),options:{isWholeLine:!0,glyphMarginClassName:this.props.isDark?"monacoBreakPointDark":"monacoBreakPoint"}})}),this.editor){const e=this.editor.getModel();e&&(this.decorations=e.deltaDecorations(this.decorations,t))}}initNewScript(t,i){var e;this.setState({name:t}),this.originalCode=i||"",(e=this.editor)==null||e.setValue(i||""),this.highlightText(this.lastSearch),this.showDecorators(),this.setEditorTypings(t)}scrollToLineIfNeeded(t){if(this.editor){const i=this.editor.getVisibleRanges();(!i||!i[0]||i[0].startLineNumber>t||t>i[0].endLineNumber)&&this.editor.revealLineInCenter(t)}}UNSAFE_componentWillReceiveProps(t){const i={};this.state.name!==t.name&&this.initNewScript(t.name,t.code),JSON.stringify(t.runningInstances)!==this.runningInstancesStr&&(this.runningInstancesStr=JSON.stringify(t.runningInstances),this.state.typingsLoaded||this.loadTypings(t.runningInstances)),this.editor&&!t.changed&&(t.code!==this.originalCode||t.code!==this.editor.getValue())&&(this.originalCode=t.code||"",this.editor.setValue(this.originalCode),this.showDecorators(),this.location&&this.scrollToLineIfNeeded(this.location.lineNumber+1)),t.searchText!==this.lastSearch&&(this.lastSearch=t.searchText||"",this.highlightText(this.lastSearch)),JSON.stringify(t.location)!==JSON.stringify(this.location)&&JSON.stringify(t.breakpoints)!==JSON.stringify(this.breakpoints)?(this.location=t.location||void 0,this.breakpoints=t.breakpoints,this.showDecorators(),this.editor&&this.location&&this.scrollToLineIfNeeded(this.location.lineNumber+1)):JSON.stringify(t.breakpoints)!==JSON.stringify(this.breakpoints)?(this.breakpoints=t.breakpoints,this.showDecorators()):JSON.stringify(t.location)!==JSON.stringify(this.location)&&(this.location=t.location||void 0,this.showDecorators(),this.editor&&this.location&&this.scrollToLineIfNeeded(this.location.lineNumber+1)),this.state.language!==(t.language||"javascript")?(this.setState({language:t.language||"javascript"}),i.language=t.language||"javascript"):this.state.readOnly!==(t.readOnly||!1)?(this.setState({readOnly:t.readOnly||!1}),i.readOnly=t.readOnly):this.state.isDark!==(t.isDark||!1)&&(this.setState({isDark:t.isDark||!1}),i.isDark=t.isDark),this.setEditorOptions(i),this.insert!==t.insert&&(this.insert=t.insert||"",this.insert&&(console.log(`Insert text: ${this.insert}`),setTimeout(e=>{this.insertTextIntoEditor(e),setTimeout(()=>this.props.onInserted&&this.props.onInserted(),100)},100,this.insert)))}onChange(){var t,i;!this.props.readOnly&&this.editor&&((i=(t=this.props).onChange)==null||i.call(t,this.editor.getValue()))}renderErrorDialog(){return this.state.showError?this.state.showError.full?n.jsxs(p.Dialog,{open:!0,maxWidth:"md",onClose:()=>this.setState({showError:null}),children:[n.jsx(p.DialogTitle,{children:this.state.showError.title||f.I18n.t("Error")}),n.jsx(p.DialogContent,{children:n.jsx("pre",{children:n.jsx("code",{children:this.state.showError.message})})}),n.jsx(p.DialogActions,{children:n.jsxs(p.Button,{variant:"contained",startIcon:n.jsx(b,{}),onClick:()=>this.setState({showError:null}),children:[f.I18n.t("Close")," "]})})]}):n.jsx(p.Snackbar,{open:!0,autoHideDuration:5e3,onClose:()=>this.setState({showError:null}),message:this.state.showError.title,action:n.jsxs(S.Fragment,{children:[n.jsx(p.Button,{color:"secondary",size:"small",onClick:()=>this.setState({showError:{...this.state.showError,full:!0}}),children:f.I18n.t("More")}),n.jsx(p.IconButton,{size:"small","aria-label":"close",color:"inherit",onClick:()=>this.setState({showError:null}),children:n.jsx(b,{fontSize:"small"})})]})}):null}render(){var t,i,e;return!((e=(i=(t=this.monaco)==null?void 0:t.languages)==null?void 0:i.typescript)!=null&&e.typescriptDefaults)||!this.props.runningInstances?(setTimeout(()=>{this.monaco=window.monaco,this.forceUpdate()},200),null):(this.props.triggerPrettier!==this.triggerPrettier&&(this.triggerPrettier=this.props.triggerPrettier,setTimeout(()=>this.doPrettier().catch(s=>console.error("Error formatting code:",s)),50)),n.jsxs("div",{ref:this.monacoDiv,style:{...this.props.style,width:"100%",height:"100%",overflow:"hidden",position:"relative"},children:[this.renderErrorDialog(),!this.state.check&&n.jsx(p.Fab,{size:"small",title:f.I18n.t("Check is not active, because javascript adapter is disabled"),style:{bottom:10,right:10,opacity:.5,position:"absolute",zIndex:1,background:"red",color:"white"},color:"secondary",children:n.jsx(C,{})})]}))}}export{R as default};
|