iobroker.javascript 9.0.6 → 9.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (26) hide show
  1. package/README.md +3 -5
  2. package/admin/assets/OpenAiDialog-CVjeP8wR.js +34 -0
  3. package/admin/assets/{Save-BKC3BS3x.js → Save-DgI3b32B.js} +1 -1
  4. package/admin/assets/{ScriptEditor-CzFTsfG9.js → ScriptEditor-CXV4FkqA.js} +1 -1
  5. package/admin/assets/{ScriptEditorVanillaMonaco-DEgxOslR.js → ScriptEditorVanillaMonaco-D-2WOvcn.js} +1 -1
  6. package/admin/assets/{createSvgIcon-BQT-7-GS.js → createSvgIcon-Dtl7HhPO.js} +3 -3
  7. package/admin/assets/{index-glyB1sbj.js → index-BwNmFzfy.js} +1 -1
  8. package/admin/assets/{index-DnqHzUyv.js → index-C5V5CZI4.js} +1 -1
  9. package/admin/assets/{index-JSzqpJXf.js → index-C8bcOa64.js} +9 -9
  10. package/admin/assets/{index-Cek-i92T.js → index-DLBeMhRC.js} +4 -4
  11. package/admin/assets/{index-BHQhuPkd.js → index-D_7ZHRw9.js} +1 -1
  12. package/admin/assets/{index-CpeX0MWe.js → index-Del0XJb9.js} +1 -1
  13. package/admin/assets/{inheritsLoose--KnFDOw1.js → inheritsLoose-C9MZGDit.js} +1 -1
  14. package/admin/assets/{useTheme-DF6qfrtI.js → useTheme-g_P2Itm2.js} +1 -1
  15. package/admin/custom/assets/{index-DxyyYdTq.js → index-B6ima1M5.js} +7 -7
  16. package/admin/custom/assets/index-CoMexdpH.js +1399 -0
  17. package/admin/custom/customComponents.js +2 -2
  18. package/admin/google-blockly/own/blocks_procedures.js +15 -9
  19. package/admin/google-blockly/own/blocks_time.js +20 -6
  20. package/admin/mf-manifest.json +1 -1
  21. package/admin/remoteEntry.js +2 -2
  22. package/admin/tab.html +4 -4
  23. package/io-package.json +14 -14
  24. package/package.json +1 -1
  25. package/admin/assets/OpenAiDialog-9N4LihWY.js +0 -34
  26. package/admin/custom/assets/index-Coei6-WB.js +0 -1399
package/README.md CHANGED
@@ -26,6 +26,9 @@ Executes Javascript, Typescript Scripts.
26
26
  <!--
27
27
  ### **WORK IN PROGRESS**
28
28
  -->
29
+ ### 9.0.7 (2025-06-29)
30
+ * (@GermanBluefox) Fixing some blocks in blockly: time, function
31
+
29
32
  ### 9.0.6 (2025-06-18)
30
33
  * (@GermanBluefox) Speed-up loading of GUI
31
34
  * (@GermanBluefox) Migrating old blocks to new format
@@ -47,11 +50,6 @@ Executes Javascript, Typescript Scripts.
47
50
  * (@GermanBluefox) Breaking change: removed "request" module
48
51
  * (@GermanBluefox) Added prettier for scripts
49
52
 
50
- ### 8.9.2 (2025-04-27)
51
-
52
- * (@GermanBluefox) Updated packages for GUI
53
- * (@GermanBluefox) Used TypeScript for an admin component
54
-
55
53
  ## License
56
54
  The MIT License (MIT)
57
55
 
@@ -0,0 +1,34 @@
1
+ import{c as ir,j as O}from"./createSvgIcon-Dtl7HhPO.js";import{i as Z}from"./iobroker_javascript__loadShare__react__loadShare__-BiJPUKBK.js";import{i as j,c as un,C as or}from"./index-C5V5CZI4.js";import{i as U,h as cr}from"./index-DLBeMhRC.js";import{_ as lr}from"./preload-helper-Dp1pzeXC.js";import{C as ur,t as hr}from"./index-Dm1jc4t6.js";import dr from"./ScriptEditorVanillaMonaco-D-2WOvcn.js";import"./_commonjsHelpers-Cpj98o6Y.js";import"./iobroker_javascript__mf_v__runtimeInit__mf_v__-CBQgOKij.js";import"./inheritsLoose-C9MZGDit.js";const fr=ir(O.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 Fn=function(){const{crypto:s}=globalThis;if(s!=null&&s.randomUUID)return Fn=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 $t(s){return typeof s=="object"&&s!==null&&("name"in s&&s.name==="AbortError"||"message"in s&&String(s.message).includes("FetchRequestCanceledException"))}const Et=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 C extends Error{}class J extends C{constructor(e,t,n,r){super(`${J.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 ft({message:n,cause:Et(t)});const a=t==null?void 0:t.error;return e===400?new Ln(e,a,n,r):e===401?new Dn(e,a,n,r):e===403?new Bn(e,a,n,r):e===404?new Wn(e,a,n,r):e===409?new Un(e,a,n,r):e===422?new qn(e,a,n,r):e===429?new Jn(e,a,n,r):e>=500?new Hn(e,a,n,r):new J(e,a,n,r)}}class z extends J{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class ft extends J{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}}class Ut extends ft{constructor({message:e}={}){super({message:e??"Request timed out."})}}class Ln extends J{}class Dn extends J{}class Bn extends J{}class Wn extends J{}class Un extends J{}class qn extends J{}class Jn extends J{}class Hn extends J{}class Xn extends C{constructor(){super("Could not parse response content as the length limit was reached")}}class Kn extends C{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class Ie extends Error{constructor(e){super(e)}}const mr=/^[a-z][a-z0-9+.-]*:/i,pr=s=>mr.test(s);let K=s=>(K=Array.isArray,K(s)),hn=K;function gr(s){return typeof s!="object"?{}:s??{}}function _r(s){if(!s)return!0;for(const e in s)return!1;return!0}function yr(s,e){return Object.prototype.hasOwnProperty.call(s,e)}function bt(s){return s!=null&&typeof s=="object"&&!Array.isArray(s)}const wr=(s,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new C(`${s} must be an integer`);if(e<0)throw new C(`${s} must be a positive integer`);return e},br=s=>{try{return JSON.parse(s)}catch{return}},De=s=>new Promise(e=>setTimeout(e,s)),we="5.8.2",Sr=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function xr(){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 Ar=()=>{var t;const s=xr();if(s==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":we,"X-Stainless-OS":fn(Deno.build.os),"X-Stainless-Arch":dn(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":fn(globalThis.process.platform??"unknown"),"X-Stainless-Arch":dn(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const e=vr();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 vr(){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 dn=s=>s==="x32"?"x32":s==="x86_64"||s==="x64"?"x64":s==="arm"?"arm":s==="aarch64"||s==="arm64"?"arm64":s?`other:${s}`:"unknown",fn=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 mn;const Cr=()=>mn??(mn=Ar());function Ir(){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 Vn(...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 Gn(s){let e=Symbol.asyncIterator in s?s[Symbol.asyncIterator]():s[Symbol.iterator]();return Vn({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 Qn(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 Rr(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 kr=({headers:s,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)}),zn="RFC3986",Yn=s=>String(s),pn={RFC1738:s=>String(s).replace(/%20/g,"+"),RFC3986:Yn},$r="RFC1738";let Ot=(s,e)=>(Ot=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Ot(s,e));const ee=(()=>{const s=[];for(let e=0;e<256;++e)s.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return s})(),St=1024,Er=(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+=St){const l=a.length>=St?a.slice(o,o+St):a,h=[];for(let _=0;_<l.length;++_){let u=l.charCodeAt(_);if(u===45||u===46||u===95||u===126||u>=48&&u<=57||u>=65&&u<=90||u>=97&&u<=122||r===$r&&(u===40||u===41)){h[h.length]=l.charAt(_);continue}if(u<128){h[h.length]=ee[u];continue}if(u<2048){h[h.length]=ee[192|u>>6]+ee[128|u&63];continue}if(u<55296||u>=57344){h[h.length]=ee[224|u>>12]+ee[128|u>>6&63]+ee[128|u&63];continue}_+=1,u=65536+((u&1023)<<10|l.charCodeAt(_)&1023),h[h.length]=ee[240|u>>18]+ee[128|u>>12&63]+ee[128|u>>6&63]+ee[128|u&63]}i+=h.join("")}return i};function Or(s){return!s||typeof s!="object"?!1:!!(s.constructor&&s.constructor.isBuffer&&s.constructor.isBuffer(s))}function gn(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 Zn={brackets(s){return String(s)+"[]"},comma:"comma",indices(s,e){return String(s)+"["+e+"]"},repeat(s){return String(s)}},es=function(s,e){Array.prototype.push.apply(s,K(e)?e:[e])};let _n;const B={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Er,encodeValuesOnly:!1,format:zn,formatter:Yn,indices:!1,serializeDate(s){return(_n??(_n=Function.prototype.call.bind(Date.prototype.toISOString)))(s)},skipNulls:!1,strictNullHandling:!1};function Pr(s){return typeof s=="string"||typeof s=="number"||typeof s=="boolean"||typeof s=="symbol"||typeof s=="bigint"}const xt={};function ts(s,e,t,n,r,a,i,o,l,h,_,u,g,d,b,w,A,E){let m=s,y=E,p=0,v=!1;for(;(y=y.get(xt))!==void 0&&!v;){const T=y.get(s);if(p+=1,typeof T<"u"){if(T===p)throw new RangeError("Cyclic object value");v=!0}typeof y.get(xt)>"u"&&(p=0)}if(typeof h=="function"?m=h(e,m):m instanceof Date?m=g==null?void 0:g(m):t==="comma"&&K(m)&&(m=gn(m,function(T){return T instanceof Date?g==null?void 0:g(T):T})),m===null){if(a)return l&&!w?l(e,B.encoder,A,"key",d):e;m=""}if(Pr(m)||Or(m)){if(l){const T=w?e:l(e,B.encoder,A,"key",d);return[(b==null?void 0:b(T))+"="+(b==null?void 0:b(l(m,B.encoder,A,"value",d)))]}return[(b==null?void 0:b(e))+"="+(b==null?void 0:b(String(m)))]}const $=[];if(typeof m>"u")return $;let I;if(t==="comma"&&K(m))w&&l&&(m=gn(m,l)),I=[{value:m.length>0?m.join(",")||null:void 0}];else if(K(h))I=h;else{const T=Object.keys(m);I=_?T.sort(_):T}const F=o?String(e).replace(/\./g,"%2E"):String(e),x=n&&K(m)&&m.length===1?F+"[]":F;if(r&&K(m)&&m.length===0)return x+"[]";for(let T=0;T<I.length;++T){const M=I[T],se=typeof M=="object"&&typeof M.value<"u"?M.value:m[M];if(i&&se===null)continue;const me=u&&o?M.replace(/\./g,"%2E"):M,N=K(m)?typeof t=="function"?t(x,me):x:x+(u?"."+me:"["+me+"]");E.set(s,p);const ie=new WeakMap;ie.set(xt,E),es($,ts(se,N,t,n,r,a,i,o,t==="comma"&&w&&K(m)?null:l,h,_,u,g,d,b,w,A,ie))}return $}function Tr(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=zn;if(typeof s.format<"u"){if(!Ot(pn,s.format))throw new TypeError("Unknown format option provided.");t=s.format}const n=pn[t];let r=B.filter;(typeof s.filter=="function"||K(s.filter))&&(r=s.filter);let a;if(s.arrayFormat&&s.arrayFormat in Zn?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 Mr(s,e={}){let t=s;const n=Tr(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=Zn[n.arrayFormat],l=o==="comma"&&n.commaRoundTrip;r||(r=Object.keys(t)),n.sort&&r.sort(n.sort);const h=new WeakMap;for(let g=0;g<r.length;++g){const d=r[g];n.skipNulls&&t[d]===null||es(i,ts(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,h))}const _=i.join(n.delimiter);let u=n.addQueryPrefix===!0?"?":"";return n.charsetSentinel&&(n.charset==="iso-8859-1"?u+="utf8=%26%2310003%3B&":u+="utf8=%E2%9C%93&"),_.length>0?u+_:""}function Nr(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 yn;function qt(s){let e;return(yn??(e=new globalThis.TextEncoder,yn=e.encode.bind(e)))(s)}let wn;function bn(s){let e;return(wn??(e=new globalThis.TextDecoder,wn=e.decode.bind(e)))(s)}var V,G;class mt{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"?qt(e):e;R(this,V,Nr([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(bn(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=bn(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;mt.NEWLINE_CHARS=new Set([`
3
+ `,"\r"]);mt.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 Fr(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}class ne{constructor(e,t){this.iterator=e,this.controller=t}static fromSSEResponse(e,t){let n=!1;async function*r(){if(n)throw new C("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let a=!1;try{for await(const i of Lr(e,t))if(!a){if(i.data.startsWith("[DONE]")){a=!0;continue}if(i.event===null||i.event.startsWith("response.")||i.event.startsWith("transcript.")){let o;try{o=JSON.parse(i.data)}catch(l){throw console.error("Could not parse message into JSON:",i.data),console.error("From chunk:",i.raw),l}if(o&&o.error)throw new J(void 0,o.error,void 0,e.headers);yield o}else{let o;try{o=JSON.parse(i.data)}catch(l){throw console.error("Could not parse message into JSON:",i.data),console.error("From chunk:",i.raw),l}if(i.event=="error")throw new J(void 0,o.error,o.message,void 0);yield{event:i.event,data:o}}}a=!0}catch(i){if($t(i))return;throw i}finally{a||t.abort()}}return new ne(r,t)}static fromReadableStream(e,t){let n=!1;async function*r(){const i=new mt,o=Qn(e);for await(const l of o)for(const h of i.decode(l))yield h;for(const l of i.flush())yield l}async function*a(){if(n)throw new C("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let i=!1;try{for await(const o of r())i||o&&(yield JSON.parse(o));i=!0}catch(o){if($t(o))return;throw o}finally{i||t.abort()}}return new ne(a,t)}[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),new ne(()=>r(t),this.controller)]}toReadableStream(){const e=this;let t;return Vn({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=qt(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*Lr(s,e){if(!s.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new C("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 C("Attempted to iterate over a response with no body");const t=new Br,n=new mt,r=Qn(s.body);for await(const a of Dr(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*Dr(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"?qt(t):t;let r=new Uint8Array(e.length+n.length);r.set(e),r.set(n,e.length),e=r;let a;for(;(a=Fr(e))!==-1;)yield e.slice(0,a),e=e.slice(a)}e.length>0&&(yield e)}class Br{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]=Wr(e,":");return r.startsWith(" ")&&(r=r.substring(1)),t==="event"?this.event=r:t==="data"&&this.data.push(r),null}}function Wr(s,e){const t=s.indexOf(e);return t!==-1?[s.substring(0,t),e,s.substring(t+e.length)]:[s,"",""]}const it={off:0,error:200,warn:300,info:400,debug:500},Sn=(s,e,t)=>{if(s){if(yr(it,s))return s;H(t).warn(`${e} was set to ${JSON.stringify(s)}, expected one of ${JSON.stringify(Object.keys(it))}`)}};function Re(){}function qe(s,e,t){return!e||it[s]>it[t]?Re:e[s].bind(e)}const Ur={error:Re,warn:Re,info:Re,debug:Re};let xn=new WeakMap;function H(s){const e=s.logger,t=s.logLevel??"off";if(!e)return Ur;const n=xn.get(e);if(n&&n[0]===t)return n[1];const r={error:qe("error",e,t),warn:qe("warn",e,t),info:qe("info",e,t),debug:qe("debug",e,t)};return xn.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);async function ns(s,e){const{response:t,requestLogID:n,retryOfRequestLogID:r,startTime:a}=e,i=await(async()=>{var u;if(e.options.stream)return H(s).debug("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller):ne.fromSSEResponse(t,e.controller);if(t.status===204)return null;if(e.options.__binaryResponse)return t;const o=t.headers.get("content-type"),l=(u=o==null?void 0:o.split(";")[0])==null?void 0:u.trim();if((l==null?void 0:l.includes("application/json"))||(l==null?void 0:l.endsWith("+json"))){const g=await t.json();return ss(g,t)}return await t.text()})();return H(s).debug(`[${n}] response parsed`,le({retryOfRequestLogID:r,url:t.url,status:t.status,body:i,durationMs:Date.now()-a})),i}function ss(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 pt extends Promise{constructor(e,t,n=ns){super(r=>{r(null)}),this.responsePromise=t,this.parseResponse=n,ke.set(this,void 0),R(this,ke,e)}_thenUnwrap(e){return new pt(c(this,ke,"f"),this.responsePromise,async(t,n)=>ss(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 Je;class rs{constructor(e,t,n,r){Je.set(this,void 0),R(this,Je,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 C("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await c(this,Je,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Je=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}}class qr extends pt{constructor(e,t,n){super(e,t,async(r,a)=>new n(r,a.response,await ns(r,a),a.options))}async*[Symbol.asyncIterator](){const e=await this;for await(const t of e)yield t}}class gt extends rs{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 rs{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:{...gr(this.options.query),after:t}}:null}}const as=()=>{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 Ne(s,e,t){return as(),new File(s,e??"unknown_file",t)}function ze(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 is=s=>s!=null&&typeof s=="object"&&typeof s[Symbol.asyncIterator]=="function",fe=async(s,e)=>({...s,body:await Hr(s.body,e)}),An=new WeakMap;function Jr(s){const e=typeof s=="function"?s:s.fetch,t=An.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 An.set(e,n),n}const Hr=async(s,e)=>{if(!await Jr(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])=>Pt(t,n,r))),t},Xr=s=>s instanceof Blob&&"name"in s,Pt=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,Ne([await t.blob()],ze(t)));else if(is(t))s.append(e,Ne([await new Response(Gn(t)).blob()],ze(t)));else if(Xr(t))s.append(e,t,ze(t));else if(Array.isArray(t))await Promise.all(t.map(n=>Pt(s,e+"[]",n)));else if(typeof t=="object")await Promise.all(Object.entries(t).map(([n,r])=>Pt(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`)}},os=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",Kr=s=>s!=null&&typeof s=="object"&&typeof s.name=="string"&&typeof s.lastModified=="number"&&os(s),Vr=s=>s!=null&&typeof s=="object"&&typeof s.url=="string"&&typeof s.blob=="function";async function Gr(s,e,t){if(as(),s=await s,Kr(s))return s instanceof File?s:Ne([await s.arrayBuffer()],s.name);if(Vr(s)){const r=await s.blob();return e||(e=new URL(s.url).pathname.split(/[\\/]/).pop()),Ne(await Tt(r),e,t)}const n=await Tt(s);if(e||(e=ze(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 Ne(n,e,t)}async function Tt(s){var t;let e=[];if(typeof s=="string"||ArrayBuffer.isView(s)||s instanceof ArrayBuffer)e.push(s);else if(os(s))e.push(s instanceof Blob?s:await s.arrayBuffer());else if(is(s))for await(const n of s)e.push(...await Tt(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}`:""}${Qr(s)}`)}return e}function Qr(s){return typeof s!="object"||s===null?"":`; props: [${Object.getOwnPropertyNames(s).map(t=>`"${t}"`).join(", ")}]`}class k{constructor(e){this._client=e}}function cs(s){return s.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const zr=(s=cs)=>function(t,...n){if(t.length===1)return t[0];let r=!1;const a=t.reduce((_,u,g)=>(/[?#]/.test(u)&&(r=!0),_+u+(g===n.length?"":(r?encodeURIComponent:s)(String(n[g])))),""),i=a.split(/[?#]/,1)[0],o=[],l=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi;let h;for(;(h=l.exec(i))!==null;)o.push({start:h.index,length:h[0].length});if(o.length>0){let _=0;const u=o.reduce((g,d)=>{const b=" ".repeat(d.start-_),w="^".repeat(d.length);return _=d.start+d.length,g+b+w},"");throw new C(`Path parameters result in path with invalid segments:
6
+ ${a}
7
+ ${u}`)}return a},f=zr(cs);let ls=class extends k{list(e,t={},n){return this._client.getAPIList(f`/chat/completions/${e}/messages`,L,{query:t,...n})}};function Yr(s){return typeof s.parse=="function"}const ot=s=>(s==null?void 0:s.role)==="assistant",us=s=>(s==null?void 0:s.role)==="tool";var Mt,Ye,Ze,$e,Ee,et,Oe,ae,Pe,ct,lt,be,hs;class Jt{constructor(){Mt.add(this),this.controller=new AbortController,Ye.set(this,void 0),Ze.set(this,()=>{}),$e.set(this,()=>{}),Ee.set(this,void 0),et.set(this,()=>{}),Oe.set(this,()=>{}),ae.set(this,{}),Pe.set(this,!1),ct.set(this,!1),lt.set(this,!1),be.set(this,!1),R(this,Ye,new Promise((e,t)=>{R(this,Ze,e,"f"),R(this,$e,t,"f")})),R(this,Ee,new Promise((e,t)=>{R(this,et,e,"f"),R(this,Oe,t,"f")})),c(this,Ye,"f").catch(()=>{}),c(this,Ee,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},c(this,Mt,"m",hs).bind(this))},0)}_connected(){this.ended||(c(this,Ze,"f").call(this),this._emit("connect"))}get ended(){return c(this,Pe,"f")}get errored(){return c(this,ct,"f")}get aborted(){return c(this,lt,"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,Pe,"f"))return;e==="end"&&(R(this,Pe,!0),c(this,et,"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,$e,"f").call(this,r),c(this,Oe,"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,$e,"f").call(this,r),c(this,Oe,"f").call(this,r),this._emit("end")}}_emitFinal(){}}Ye=new WeakMap,Ze=new WeakMap,$e=new WeakMap,Ee=new WeakMap,et=new WeakMap,Oe=new WeakMap,ae=new WeakMap,Pe=new WeakMap,ct=new WeakMap,lt=new WeakMap,be=new WeakMap,Mt=new WeakSet,hs=function(e){if(R(this,ct,!0),e instanceof Error&&e.name==="AbortError"&&(e=new z),e instanceof z)return R(this,lt,!0),this._emit("abort",e);if(e instanceof C)return this._emit("error",e);if(e instanceof Error){const t=new C(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new C(String(e)))};function Ht(s){return(s==null?void 0:s.$brand)==="auto-parseable-response-format"}function Be(s){return(s==null?void 0:s.$brand)==="auto-parseable-tool"}function Zr(s,e){return!e||!ds(e)?{...s,choices:s.choices.map(t=>({...t,message:{...t.message,parsed:null,...t.message.tool_calls?{tool_calls:t.message.tool_calls}:void 0}}))}:Xt(s,e)}function Xt(s,e){const t=s.choices.map(n=>{var r;if(n.finish_reason==="length")throw new Xn;if(n.finish_reason==="content_filter")throw new Kn;return{...n,message:{...n.message,...n.message.tool_calls?{tool_calls:((r=n.message.tool_calls)==null?void 0:r.map(a=>ta(e,a)))??void 0}:void 0,parsed:n.message.content&&!n.message.refusal?ea(e,n.message.content):null}}});return{...s,choices:t}}function ea(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 ta(s,e){var n;const t=(n=s.tools)==null?void 0:n.find(r=>{var a;return((a=r.function)==null?void 0:a.name)===e.function.name});return{...e,function:{...e.function,parsed_arguments:Be(t)?t.$parseRaw(e.function.arguments):t!=null&&t.function.strict?JSON.parse(e.function.arguments):null}}}function na(s,e){var n;if(!s)return!1;const t=(n=s.tools)==null?void 0:n.find(r=>{var a;return((a=r.function)==null?void 0:a.name)===e.function.name});return Be(t)||(t==null?void 0:t.function.strict)||!1}function ds(s){var e;return Ht(s.response_format)?!0:((e=s.tools)==null?void 0:e.some(t=>Be(t)||t.type==="function"&&t.function.strict===!0))??!1}function sa(s){for(const e of s??[]){if(e.type!=="function")throw new C(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new C(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var X,Nt,ut,jt,Ft,Lt,fs,ms;const ra=10;class ps extends Jt{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),us(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(ot(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 C("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),c(this,X,"m",Nt).call(this)}async finalMessage(){return await this.done(),c(this,X,"m",ut).call(this)}async finalFunctionToolCall(){return await this.done(),c(this,X,"m",jt).call(this)}async finalFunctionToolCallResult(){return await this.done(),c(this,X,"m",Ft).call(this)}async totalUsage(){return await this.done(),c(this,X,"m",Lt).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",ut).call(this);t&&this._emit("finalMessage",t);const n=c(this,X,"m",Nt).call(this);n&&this._emit("finalContent",n);const r=c(this,X,"m",jt).call(this);r&&this._emit("finalFunctionToolCall",r);const a=c(this,X,"m",Ft).call(this);a!=null&&this._emit("finalFunctionToolCallResult",a),this._chatCompletions.some(i=>i.usage)&&this._emit("totalUsage",c(this,X,"m",Lt).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",fs).call(this,t);const a=await e.chat.completions.create({...t,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(Xt(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"&&((d=a==null?void 0:a.function)==null?void 0:d.name),{maxChatCompletions:h=ra}=n||{},_=t.tools.map(A=>{if(Be(A)){if(!A.$callback)throw new C("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:A.$callback,name:A.function.name,description:A.function.description||"",parameters:A.function.parameters,parse:A.$parseRaw,strict:!0}}}return A}),u={};for(const A of _)A.type==="function"&&(u[A.function.name||A.function.function.name]=A.function);const g="tools"in t?_.map(A=>A.type==="function"?{type:"function",function:{name:A.function.name||A.function.function.name,parameters:A.function.parameters,description:A.function.description,strict:A.function.strict}}:A):void 0;for(const A of t.messages)this._addMessage(A,!1);for(let A=0;A<h;++A){const m=(b=(await this._createChatCompletion(e,{...o,tool_choice:a,tools:g,messages:[...this.messages]},n)).choices[0])==null?void 0:b.message;if(!m)throw new C("missing message in ChatCompletion response");if(!((w=m.tool_calls)!=null&&w.length))return;for(const y of m.tool_calls){if(y.type!=="function")continue;const p=y.id,{name:v,arguments:$}=y.function,I=u[v];if(I){if(l&&l!==v){const M=`Invalid tool_call: ${JSON.stringify(v)}. ${JSON.stringify(l)} requested. Please try again`;this._addMessage({role:r,tool_call_id:p,content:M});continue}}else{const M=`Invalid tool_call: ${JSON.stringify(v)}. Available options are: ${Object.keys(u).map(se=>JSON.stringify(se)).join(", ")}. Please try again`;this._addMessage({role:r,tool_call_id:p,content:M});continue}let F;try{F=Yr(I)?await I.parse($):$}catch(M){const se=M instanceof Error?M.message:String(M);this._addMessage({role:r,tool_call_id:p,content:se});continue}const x=await I.function(F,this),T=c(this,X,"m",ms).call(this,x);if(this._addMessage({role:r,tool_call_id:p,content:T}),l)return}}}}X=new WeakSet,Nt=function(){return c(this,X,"m",ut).call(this).content??null},ut=function(){let e=this.messages.length;for(;e-- >0;){const t=this.messages[e];if(ot(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new C("stream ended without producing a ChatCompletionMessage with role=assistant")},jt=function(){var e,t;for(let n=this.messages.length-1;n>=0;n--){const r=this.messages[n];if(ot(r)&&((e=r==null?void 0:r.tool_calls)!=null&&e.length))return(t=r.tool_calls.at(-1))==null?void 0:t.function}},Ft=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(us(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}},Lt=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},fs=function(e){if(e.n!=null&&e.n>1)throw new C("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},ms=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};class Kt extends ps{static runTools(e,t,n){const r=new Kt,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),ot(e)&&e.content&&this._emit("content",e.content)}}const gs=1,_s=2,ys=4,ws=8,bs=16,Ss=32,xs=64,As=128,vs=256,Cs=As|vs,Is=bs|Ss|Cs|xs,Rs=gs|_s|Is,ks=ys|ws,aa=Rs|ks,W={STR:gs,NUM:_s,ARR:ys,OBJ:ws,NULL:bs,BOOL:Ss,NAN:xs,INFINITY:As,MINUS_INFINITY:vs,INF:Cs,SPECIAL:Is,ATOM:Rs,COLLECTION:ks,ALL:aa};class ia extends Error{}class oa extends Error{}function ca(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 la(s.trim(),e)}const la=(s,e)=>{const t=s.length;let n=0;const r=g=>{throw new ia(`${g} at position ${n}`)},a=g=>{throw new oa(`${g} at position ${n}`)},i=()=>(u(),n>=t&&r("Unexpected end of input"),s[n]==='"'?o():s[n]==="{"?l():s[n]==="["?h():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):_()),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++,u();const g={};try{for(;s[n]!=="}";){if(u(),n>=t&&W.OBJ&e)return g;const d=o();u(),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}u(),s[n]===","&&n++}}catch{if(W.OBJ&e)return g;r("Expected '}' at end of object")}return n++,g},h=()=>{n++;const g=[];try{for(;s[n]!=="]";)g.push(i()),u(),s[n]===","&&n++}catch{if(W.ARR&e)return g;r("Expected ']' at end of array")}return n++,g},_=()=>{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))}}},u=()=>{for(;n<t&&`
8
+ \r `.includes(s[n]);)n++};return i()},vn=s=>ca(s,W.ALL^W.NUM);var D,re,pe,oe,At,He,vt,Ct,It,Xe,Rt,Cn;class Le extends ps{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 Le(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,n){const r=new Le(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",At).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",vt).call(this,o);if((i=a.controller.signal)!=null&&i.aborted)throw new z;return this._addChatCompletion(c(this,D,"m",Xe).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",At).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",Xe).call(this)),c(this,D,"m",vt).call(this,o),a=o.id;if((i=r.controller.signal)!=null&&i.aborted)throw new z;return this._addChatCompletion(c(this,D,"m",Xe).call(this))}[(re=new WeakMap,pe=new WeakMap,oe=new WeakMap,D=new WeakSet,At=function(){this.ended||R(this,oe,void 0)},He=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)},vt=function(t){var r,a,i,o,l,h,_,u,g,d,b,w,A,E,m;if(this.ended)return;const n=c(this,D,"m",Cn).call(this,t);this._emit("chunk",t,n);for(const y of t.choices){const p=n.choices[y.index];y.delta.content!=null&&((r=p.message)==null?void 0:r.role)==="assistant"&&((a=p.message)!=null&&a.content)&&(this._emit("content",y.delta.content,p.message.content),this._emit("content.delta",{delta:y.delta.content,snapshot:p.message.content,parsed:p.message.parsed})),y.delta.refusal!=null&&((i=p.message)==null?void 0:i.role)==="assistant"&&((o=p.message)!=null&&o.refusal)&&this._emit("refusal.delta",{delta:y.delta.refusal,snapshot:p.message.refusal}),((l=y.logprobs)==null?void 0:l.content)!=null&&((h=p.message)==null?void 0:h.role)==="assistant"&&this._emit("logprobs.content.delta",{content:(_=y.logprobs)==null?void 0:_.content,snapshot:((u=p.logprobs)==null?void 0:u.content)??[]}),((g=y.logprobs)==null?void 0:g.refusal)!=null&&((d=p.message)==null?void 0:d.role)==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:(b=y.logprobs)==null?void 0:b.refusal,snapshot:((w=p.logprobs)==null?void 0:w.refusal)??[]});const v=c(this,D,"m",He).call(this,p);p.finish_reason&&(c(this,D,"m",It).call(this,p),v.current_tool_call_index!=null&&c(this,D,"m",Ct).call(this,p,v.current_tool_call_index));for(const $ of y.delta.tool_calls??[])v.current_tool_call_index!==$.index&&(c(this,D,"m",It).call(this,p),v.current_tool_call_index!=null&&c(this,D,"m",Ct).call(this,p,v.current_tool_call_index)),v.current_tool_call_index=$.index;for(const $ of y.delta.tool_calls??[]){const I=(A=p.message.tool_calls)==null?void 0:A[$.index];I!=null&&I.type&&((I==null?void 0:I.type)==="function"?this._emit("tool_calls.function.arguments.delta",{name:(E=I.function)==null?void 0:E.name,index:$.index,arguments:I.function.arguments,parsed_arguments:I.function.parsed_arguments,arguments_delta:((m=$.function)==null?void 0:m.arguments)??""}):(I==null||I.type,void 0))}}},Ct=function(t,n){var i,o,l;if(c(this,D,"m",He).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 h=(l=(o=c(this,re,"f"))==null?void 0:o.tools)==null?void 0:l.find(_=>_.type==="function"&&_.function.name===a.function.name);this._emit("tool_calls.function.arguments.done",{name:a.function.name,index:n,arguments:a.function.arguments,parsed_arguments:Be(h)?h.$parseRaw(a.function.arguments):h!=null&&h.function.strict?JSON.parse(a.function.arguments):null})}else a.type},It=function(t){var r,a;const n=c(this,D,"m",He).call(this,t);if(t.message.content&&!n.content_done){n.content_done=!0;const i=c(this,D,"m",Rt).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}))},Xe=function(){if(this.ended)throw new C("stream has ended, this shouldn't happen");const t=c(this,oe,"f");if(!t)throw new C("request ended without sending any chunks");return R(this,oe,void 0),R(this,pe,[]),ua(t,c(this,re,"f"))},Rt=function(){var n;const t=(n=c(this,re,"f"))==null?void 0:n.response_format;return Ht(t)?t:null},Cn=function(t){var n,r,a,i;let o=c(this,oe,"f");const{choices:l,...h}=t;o?Object.assign(o,h):o=R(this,oe,{...h,choices:[]});for(const{delta:_,finish_reason:u,index:g,logprobs:d=null,...b}of t.choices){let w=o.choices[g];if(w||(w=o.choices[g]={finish_reason:u,index:g,message:{},logprobs:d,...b}),d)if(!w.logprobs)w.logprobs=Object.assign({},d);else{const{content:$,refusal:I,...F}=d;Object.assign(w.logprobs,F),$&&((n=w.logprobs).content??(n.content=[]),w.logprobs.content.push(...$)),I&&((r=w.logprobs).refusal??(r.refusal=[]),w.logprobs.refusal.push(...I))}if(u&&(w.finish_reason=u,c(this,re,"f")&&ds(c(this,re,"f")))){if(u==="length")throw new Xn;if(u==="content_filter")throw new Kn}if(Object.assign(w,b),!_)continue;const{content:A,refusal:E,function_call:m,role:y,tool_calls:p,...v}=_;if(Object.assign(w.message,v),E&&(w.message.refusal=(w.message.refusal||"")+E),y&&(w.message.role=y),m&&(w.message.function_call?(m.name&&(w.message.function_call.name=m.name),m.arguments&&((a=w.message.function_call).arguments??(a.arguments=""),w.message.function_call.arguments+=m.arguments)):w.message.function_call=m),A&&(w.message.content=(w.message.content||"")+A,!w.message.refusal&&c(this,D,"m",Rt).call(this)&&(w.message.parsed=vn(w.message.content))),p){w.message.tool_calls||(w.message.tool_calls=[]);for(const{index:$,id:I,type:F,function:x,...T}of p){const M=(i=w.message.tool_calls)[$]??(i[$]={});Object.assign(M,T),I&&(M.id=I),F&&(M.type=F),x&&(M.function??(M.function={name:x.name??"",arguments:""})),x!=null&&x.name&&(M.function.name=x.name),x!=null&&x.arguments&&(M.function.arguments+=x.arguments,na(c(this,re,"f"),M)&&(M.function.parsed_arguments=vn(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 ua(s,e){const{id:t,choices:n,created:r,model:a,system_fingerprint:i,...o}=s,l={...o,id:t,choices:n.map(({message:h,finish_reason:_,index:u,logprobs:g,...d})=>{if(!_)throw new C(`missing finish_reason for choice ${u}`);const{content:b=null,function_call:w,tool_calls:A,...E}=h,m=h.role;if(!m)throw new C(`missing role for choice ${u}`);if(w){const{arguments:y,name:p}=w;if(y==null)throw new C(`missing function_call.arguments for choice ${u}`);if(!p)throw new C(`missing function_call.name for choice ${u}`);return{...d,message:{content:b,function_call:{arguments:y,name:p},role:m,refusal:h.refusal??null},finish_reason:_,index:u,logprobs:g}}return A?{...d,index:u,finish_reason:_,logprobs:g,message:{...E,role:m,content:b,refusal:h.refusal??null,tool_calls:A.map((y,p)=>{const{function:v,type:$,id:I,...F}=y,{arguments:x,name:T,...M}=v||{};if(I==null)throw new C(`missing choices[${u}].tool_calls[${p}].id
9
+ ${Ke(s)}`);if($==null)throw new C(`missing choices[${u}].tool_calls[${p}].type
10
+ ${Ke(s)}`);if(T==null)throw new C(`missing choices[${u}].tool_calls[${p}].function.name
11
+ ${Ke(s)}`);if(x==null)throw new C(`missing choices[${u}].tool_calls[${p}].function.arguments
12
+ ${Ke(s)}`);return{...F,id:I,type:$,function:{...M,name:T,arguments:x}}})}}:{...d,message:{...E,content:b,role:m,refusal:h.refusal??null},finish_reason:_,index:u,logprobs:g}}),created:r,model:a,object:"chat.completion",...i?{system_fingerprint:i}:{}};return Zr(l,e)}function Ke(s){return JSON.stringify(s)}class ht extends Le{static fromReadableStream(e){const t=new ht(null);return t._run(()=>t._fromReadableStream(e)),t}static runTools(e,t,n){const r=new ht(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 Vt=class extends k{constructor(){super(...arguments),this.messages=new ls(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 sa(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=>Xt(n,e))}runTools(e,t){return e.stream?ht.runTools(this._client,e,t):Kt.runTools(this._client,e,t)}stream(e,t){return Le.createChatCompletion(this._client,e,t)}};Vt.Messages=ls;class Gt extends k{constructor(){super(...arguments),this.completions=new Vt(this._client)}}Gt.Completions=Vt;const $s=Symbol("brand.privateNullableHeaders");function*ha(s){if(!s)return;if($s 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():hn(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=hn(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 ha(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{[$s]:!0,values:e,nulls:t}};class Es extends k{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 Os extends k{create(e,t){return this._client.post("/audio/transcriptions",fe({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}}class Ps extends k{create(e,t){return this._client.post("/audio/translations",fe({body:e,...t,__metadata:{model:e.model}},this._client))}}class We extends k{constructor(){super(...arguments),this.transcriptions=new Os(this._client),this.translations=new Ps(this._client),this.speech=new Es(this._client)}}We.Transcriptions=Os;We.Translations=Ps;We.Speech=Es;class Ts extends k{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 Ms extends k{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 Ns extends k{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 js extends k{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])})}}class _t extends k{constructor(){super(...arguments),this.sessions=new Ns(this._client),this.transcriptionSessions=new js(this._client)}}_t.Sessions=Ns;_t.TranscriptionSessions=js;class Fs extends k{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 Ls extends k{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 da=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 kt={};const ge=s=>{var e,t,n,r;if(typeof globalThis.process<"u")return((e=kt==null?void 0:kt[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 q,he,Dt,te,tt,Y,de,xe,ue,dt,Q,nt,st,je,Te,Me,In,Rn,kn,$n,En,On,Pn;class Fe extends Jt{constructor(){super(...arguments),q.add(this),Dt.set(this,[]),te.set(this,{}),tt.set(this,{}),Y.set(this,void 0),de.set(this,void 0),xe.set(this,void 0),ue.set(this,void 0),dt.set(this,void 0),Q.set(this,void 0),nt.set(this,void 0),st.set(this,void 0),je.set(this,void 0)}[(Dt=new WeakMap,te=new WeakMap,tt=new WeakMap,Y=new WeakMap,de=new WeakMap,xe=new WeakMap,ue=new WeakMap,dt=new WeakMap,Q=new WeakMap,nt=new WeakMap,st=new WeakMap,je=new WeakMap,q=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,q,"m",Te).call(this,i);if((a=r.controller.signal)!=null&&a.aborted)throw new z;return this._addRun(c(this,q,"m",Me).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 h of o)c(this,q,"m",Te).call(this,h);if((l=o.controller.signal)!=null&&l.aborted)throw new z;return this._addRun(c(this,q,"m",Me).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,nt,"f")}currentRun(){return c(this,st,"f")}currentMessageSnapshot(){return c(this,Y,"f")}currentRunStepSnapshot(){return c(this,je,"f")}async finalRunSteps(){return await this.done(),Object.values(c(this,te,"f"))}async finalMessages(){return await this.done(),Object.values(c(this,tt,"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,q,"m",Te).call(this,l);if((o=i.controller.signal)!=null&&o.aborted)throw new z;return this._addRun(c(this,q,"m",Me).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 h of o)c(this,q,"m",Te).call(this,h);if((l=o.controller.signal)!=null&&l.aborted)throw new z;return this._addRun(c(this,q,"m",Me).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(bt(a)&&bt(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(!bt(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=Fe,Te=function(e){if(!this.ended)switch(R(this,nt,e),c(this,q,"m",kn).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,q,"m",Pn).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,q,"m",Rn).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,q,"m",In).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},Me=function(){if(this.ended)throw new C("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")},In=function(e){const[t,n]=c(this,q,"m",En).call(this,e,c(this,Y,"f"));R(this,Y,t),c(this,tt,"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,xe,"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,xe,r.index)}R(this,ue,t.content[r.index])}break;case"thread.message.completed":case"thread.message.incomplete":if(c(this,xe,"f")!==void 0){const r=e.data.content[c(this,xe,"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)}},Rn=function(e){const t=c(this,q,"m",$n).call(this,e);switch(R(this,je,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,dt,"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,dt,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,je,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}},kn=function(e){c(this,Dt,"f").push(e),this._emit("event",e)},$n=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")},En=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,q,"m",On).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")},On=function(e,t){return he.accumulateDelta(t,e)},Pn=function(e){switch(R(this,st,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 Qt=class extends k{constructor(){super(...arguments),this.steps=new Ls(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 Fe.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 h=o.headers.get("openai-poll-after-ms");if(h){const _=parseInt(h);isNaN(_)||(l=_)}}await De(l);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return i}}}stream(e,t,n){return Fe.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 Fe.createToolAssistantStream(e,this._client.beta.threads.runs,t,n)}};Qt.Steps=Ls;class yt extends k{constructor(){super(...arguments),this.runs=new Qt(this._client),this.messages=new Fs(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 Fe.createThreadAssistantStream(e,this._client.beta.threads,t)}}yt.Runs=Qt;yt.Messages=Fs;class Ue extends k{constructor(){super(...arguments),this.realtime=new _t(this._client),this.assistants=new Ms(this._client),this.threads=new yt(this._client)}}Ue.Realtime=_t;Ue.Assistants=Ms;Ue.Threads=yt;class Ds extends k{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}}class Bs extends k{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 zt=class extends k{constructor(){super(...arguments),this.content=new Bs(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])})}};zt.Content=Bs;class Yt extends k{constructor(){super(...arguments),this.files=new zt(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])})}}Yt.Files=zt;class Ws extends k{create(e,t){const n=!!e.encoding_format;let r=n?e.encoding_format:"base64";n&&H(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:(H(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=da(l)}),i)))}}class Us extends k{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 Zt extends k{constructor(){super(...arguments),this.outputItems=new Us(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)}}Zt.OutputItems=Us;class en extends k{constructor(){super(...arguments),this.runs=new Zt(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)}}en.Runs=Zt;let qs=class extends k{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=30*60*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 De(t),i=await this.retrieve(e),Date.now()-a>n)throw new Ut({message:`Giving up on waiting for file ${e} to finish processing after ${n} milliseconds.`});return i}};class Js extends k{}let Hs=class extends k{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 tn extends k{constructor(){super(...arguments),this.graders=new Hs(this._client)}}tn.Graders=Hs;class Xs extends k{create(e,t,n){return this._client.getAPIList(f`/fine_tuning/checkpoints/${e}/permissions`,gt,{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 nn=class extends k{constructor(){super(...arguments),this.permissions=new Xs(this._client)}};nn.Permissions=Xs;class Ks extends k{list(e,t={},n){return this._client.getAPIList(f`/fine_tuning/jobs/${e}/checkpoints`,L,{query:t,...n})}}class sn extends k{constructor(){super(...arguments),this.checkpoints=new Ks(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)}}sn.Checkpoints=Ks;class Ae extends k{constructor(){super(...arguments),this.methods=new Js(this._client),this.jobs=new sn(this._client),this.checkpoints=new nn(this._client),this.alpha=new tn(this._client)}}Ae.Methods=Js;Ae.Jobs=sn;Ae.Checkpoints=nn;Ae.Alpha=tn;class Vs extends k{}class rn extends k{constructor(){super(...arguments),this.graderModels=new Vs(this._client)}}rn.GraderModels=Vs;class Gs extends k{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},this._client))}generate(e,t){return this._client.post("/images/generations",{body:e,...t})}}class Qs extends k{retrieve(e,t){return this._client.get(f`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",gt,e)}delete(e,t){return this._client.delete(f`/models/${e}`,t)}}class zs extends k{create(e,t){return this._client.post("/moderations",{body:e,...t})}}function fa(s,e){return!e||!pa(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)}:Ys(s,e)}function Ys(s,e){const t=s.output.map(r=>{if(r.type==="function_call")return{...r,parsed_arguments:ya(e,r)};if(r.type==="message"){const a=r.content.map(i=>i.type==="output_text"?{...i,parsed:ma(e,i.text)}:i);return{...r,content:a}}return r}),n=Object.assign({},s,{output:t});return Object.getOwnPropertyDescriptor(s,"output_text")||Bt(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 ma(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 pa(s){var e;return!!Ht((e=s.text)==null?void 0:e.format)}function ga(s){return(s==null?void 0:s.$brand)==="auto-parseable-tool"}function _a(s,e){return s.find(t=>t.type==="function"&&t.name===e)}function ya(s,e){const t=_a(s.tools??[],e.name);return{...e,...e,parsed_arguments:ga(t)?t.$parseRaw(e.arguments):t!=null&&t.strict?JSON.parse(e.arguments):null}}function Bt(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,Ve,ce,Ge,Tn,Mn,Nn,jn;class an extends Jt{constructor(e){super(),_e.add(this),Ve.set(this,void 0),ce.set(this,void 0),Ge.set(this,void 0),R(this,Ve,e)}static createResponse(e,t,n){const r=new an(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",Tn).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",Mn).call(this,l,i);if((o=a.controller.signal)!=null&&o.aborted)throw new z;return c(this,_e,"m",Nn).call(this)}[(Ve=new WeakMap,ce=new WeakMap,Ge=new WeakMap,_e=new WeakSet,Tn=function(){this.ended||R(this,ce,void 0)},Mn=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",jn).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 C(`missing output at index ${t.output_index}`);if(i.type==="message"){const o=i.content[t.content_index];if(!o)throw new C(`missing content at index ${t.content_index}`);if(o.type!=="output_text")throw new C(`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 C(`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}},Nn=function(){if(this.ended)throw new C("stream has ended, this shouldn't happen");const t=c(this,ce,"f");if(!t)throw new C("request ended without sending any events");R(this,ce,void 0);const n=wa(t,c(this,Ve,"f"));return R(this,Ge,n),n},jn=function(t){let n=c(this,ce,"f");if(!n){if(t.type!=="response.created")throw new C(`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 r=n.output[t.output_index];if(!r)throw new C(`missing output at index ${t.output_index}`);r.type==="message"&&r.content.push(t.part);break}case"response.output_text.delta":{const r=n.output[t.output_index];if(!r)throw new C(`missing output at index ${t.output_index}`);if(r.type==="message"){const a=r.content[t.content_index];if(!a)throw new C(`missing content at index ${t.content_index}`);if(a.type!=="output_text")throw new C(`expected content to be 'output_text', got ${a.type}`);a.text+=t.delta}break}case"response.function_call_arguments.delta":{const r=n.output[t.output_index];if(!r)throw new C(`missing output at index ${t.output_index}`);r.type==="function_call"&&(r.arguments+=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,Ge,"f");if(!e)throw new C("stream ended without producing a ChatCompletion");return e}}function wa(s,e){return fa(s,e)}class Zs extends k{list(e,t={},n){return this._client.getAPIList(f`/responses/${e}/input_items`,L,{query:t,...n})}}class on extends k{constructor(){super(...arguments),this.inputItems=new Zs(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"&&Bt(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"&&Bt(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=>Ys(n,e))}stream(e,t){return an.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(f`/responses/${e}/cancel`,t)}}on.InputItems=Zs;class er extends k{create(e,t,n){return this._client.post(f`/uploads/${e}/parts`,fe({body:t,...n},this._client))}}class cn extends k{constructor(){super(...arguments),this.parts=new er(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})}}cn.Parts=er;const ba=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 tr extends k{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 h=o.headers.get("openai-poll-after-ms");if(h){const _=parseInt(h);isNaN(_)||(l=_)}}await De(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(),h=[...n];async function _(g){for(let d of g){const b=await o.files.create({file:d,purpose:"assistants"},r);h.push(b.id)}}const u=Array(i).fill(l).map(_);return await ba(u),await this.createAndPoll(e,{file_ids:h})}}class nr extends k{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 h=i.response.headers.get("openai-poll-after-ms");if(h){const _=parseInt(h);isNaN(_)||(l=_)}}await De(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`,gt,{...n,headers:S([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}}class wt extends k{constructor(){super(...arguments),this.files=new nr(this._client),this.fileBatches=new tr(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`,gt,{body:t,method:"post",...n,headers:S([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}}wt.Files=nr;wt.FileBatches=tr;var Se,sr,rt;class rr extends k{constructor(){super(...arguments),Se.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,Se,"m",sr).call(this,n);const a=S([t]).values,i=c(this,Se,"m",rt).call(this,a,"webhook-signature"),o=c(this,Se,"m",rt).call(this,a,"webhook-timestamp"),l=c(this,Se,"m",rt).call(this,a,"webhook-id"),h=parseInt(o,10);if(isNaN(h))throw new Ie("Invalid webhook timestamp format");const _=Math.floor(Date.now()/1e3);if(_-h>r)throw new Ie("Webhook timestamp is too old");if(h>_+r)throw new Ie("Webhook timestamp is too new");const u=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 u)try{const A=Buffer.from(w,"base64");if(await crypto.subtle.verify("HMAC",b,A,new TextEncoder().encode(d)))return}catch{continue}throw new Ie("The given webhook signature does not match the expected signature")}}Se=new WeakSet,sr=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")},rt=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 Wt,ln,at,ar;class P{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(Wt.add(this),at.set(this,void 0),this.completions=new Ds(this),this.chat=new Gt(this),this.embeddings=new Ws(this),this.files=new qs(this),this.images=new Gs(this),this.audio=new We(this),this.moderations=new zs(this),this.models=new Qs(this),this.fineTuning=new Ae(this),this.graders=new rn(this),this.vectorStores=new wt(this),this.webhooks=new rr(this),this.beta=new Ue(this),this.batches=new Ts(this),this.uploads=new cn(this),this.responses=new on(this),this.evals=new en(this),this.containers=new Yt(this),t===void 0)throw new C("The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' }).");const o={apiKey:t,organization:n,project:r,webhookSecret:a,...i,baseURL:e||"https://api.openai.com/v1"};if(!o.dangerouslyAllowBrowser&&Sr())throw new C(`It looks like you're running in a browser-like environment.
13
+
14
+ This is disabled by default, as it risks exposing your secret API credentials to attackers.
15
+ If you understand the risks and have appropriate mitigations in place,
16
+ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
17
+
18
+ new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
19
+
20
+ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
21
+ `);this.baseURL=o.baseURL,this.timeout=o.timeout??ln.DEFAULT_TIMEOUT,this.logger=o.logger??console;const l="warn";this.logLevel=l,this.logLevel=Sn(o.logLevel,"ClientOptions.logLevel",this)??Sn(ge("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??l,this.fetchOptions=o.fetchOptions,this.maxRetries=o.maxRetries??2,this.fetch=o.fetch??Ir(),R(this,at,kr),this._options=o,this.apiKey=t,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}){}authHeaders(e){return S([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return Mr(e,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${we}`}defaultIdempotencyKey(){return`stainless-node-retry-${Fn()}`}makeStatusError(e,t,n,r){return J.generate(e,t,n,r)}buildURL(e,t,n){const r=!c(this,Wt,"m",ar).call(this)&&n||this.baseURL,a=pr(e)?new URL(e):new URL(r+(r.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),i=this.defaultQuery();return _r(i)||(t={...i,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(a.search=this.stringifyQuery(t)),a.toString()}async prepareOptions(e){}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 pt(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,n){var E,m;const r=await e,a=r.maxRetries??this.maxRetries;t==null&&(t=a),await this.prepareOptions(r);const{req:i,url:o,timeout:l}=this.buildRequest(r,{retryCount:a-t});await this.prepareRequest(i,{url:o,options:r});const h="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),_=n===void 0?"":`, retryOf: ${n}`,u=Date.now();if(H(this).debug(`[${h}] 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(Et),b=Date.now();if(d instanceof Error){const y=`retrying, ${t} attempts remaining`;if((m=r.signal)!=null&&m.aborted)throw new z;const p=$t(d)||/timed? ?out/i.test(String(d)+("cause"in d?String(d.cause):""));if(t)return H(this).info(`[${h}] connection ${p?"timed out":"failed"} - ${y}`),H(this).debug(`[${h}] connection ${p?"timed out":"failed"} (${y})`,le({retryOfRequestLogID:n,url:o,durationMs:b-u,message:d.message})),this.retryRequest(r,t,n??h);throw H(this).info(`[${h}] connection ${p?"timed out":"failed"} - error; no more retries left`),H(this).debug(`[${h}] connection ${p?"timed out":"failed"} (error; no more retries left)`,le({retryOfRequestLogID:n,url:o,durationMs:b-u,message:d.message})),p?new Ut:new ft({cause:d})}const w=[...d.headers.entries()].filter(([y])=>y==="x-request-id").map(([y,p])=>", "+y+": "+JSON.stringify(p)).join(""),A=`[${h}${_}${w}] ${i.method} ${o} ${d.ok?"succeeded":"failed"} with status ${d.status} in ${b-u}ms`;if(!d.ok){const y=this.shouldRetry(d);if(t&&y){const x=`retrying, ${t} attempts remaining`;return await Rr(d.body),H(this).info(`${A} - ${x}`),H(this).debug(`[${h}] response error (${x})`,le({retryOfRequestLogID:n,url:d.url,status:d.status,headers:d.headers,durationMs:b-u})),this.retryRequest(r,t,n??h,d.headers)}const p=y?"error; no more retries left":"error; not retryable";H(this).info(`${A} - ${p}`);const v=await d.text().catch(x=>Et(x).message),$=br(v),I=$?void 0:v;throw H(this).debug(`[${h}] response error (${p})`,le({retryOfRequestLogID:n,url:d.url,status:d.status,headers:d.headers,message:I,durationMs:Date.now()-u})),this.makeStatusError(d.status,$,I,d.headers)}return H(this).info(A),H(this).debug(`[${h}] response start`,le({retryOfRequestLogID:n,url:d.url,status:d.status,headers:d.headers,durationMs:b-u})),{response:d,options:r,controller:g,requestLogID:h,retryOfRequestLogID:n,startTime:u}}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 qr(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),h=globalThis.ReadableStream&&o.body instanceof globalThis.ReadableStream||typeof o.body=="object"&&o.body!==null&&Symbol.asyncIterator in o.body,_={signal:r.signal,...h?{duplex:"half"}:{},method:"GET",...o};i&&(_.method=i.toUpperCase());try{return await this.fetch.call(void 0,e,_)}finally{clearTimeout(l)}}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 De(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}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&&wr("timeout",n.timeout),n.timeout=n.timeout??this.timeout;const{bodyHeaders:h,body:_}=this.buildBody({options:n}),u=this.buildHeaders({options:e,method:r,bodyHeaders:h,retryCount:t});return{req:{method:r,headers:u,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&_ instanceof globalThis.ReadableStream&&{duplex:"half"},..._&&{body:_},...this.fetchOptions??{},...n.fetchOptions??{}},url:l,timeout:n.timeout}}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))}:{},...Cr(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},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")||e instanceof 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:Gn(e)}:c(this,at,"f").call(this,{body:e,headers:n})}}ln=P,at=new WeakMap,Wt=new WeakSet,ar=function(){return this.baseURL!=="https://api.openai.com/v1"};P.OpenAI=ln;P.DEFAULT_TIMEOUT=6e5;P.OpenAIError=C;P.APIError=J;P.APIConnectionError=ft;P.APIConnectionTimeoutError=Ut;P.APIUserAbortError=z;P.NotFoundError=Wn;P.ConflictError=Un;P.RateLimitError=Jn;P.BadRequestError=Ln;P.AuthenticationError=Dn;P.InternalServerError=Hn;P.PermissionDeniedError=Bn;P.UnprocessableEntityError=qn;P.InvalidWebhookSignatureError=Ie;P.toFile=Gr;P.Completions=Ds;P.Chat=Gt;P.Embeddings=Ws;P.Files=qs;P.Images=Gs;P.Audio=We;P.Moderations=zs;P.Models=Qs;P.FineTuning=Ae;P.Graders=rn;P.VectorStores=wt;P.Webhooks=rr;P.Beta=Ue;P.Batches=Ts;P.Uploads=cn;P.Responses=on;P.Evals=en;P.Containers=Yt;const Sa=lr(()=>import("./docs-BrInh2Pn.js"),[],import.meta.url);let Qe=null;async function xa(s){if(Qe)return Qe;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 Qe=Object.assign(e,t,n,r,a),Qe}function ye(s,e){return s&&typeof s=="object"?s[e]||s.en:s||""}async function Aa(s){var b,w,A,E;const e=U.I18n.getLanguage(),t=await xa(s),n=Object.keys(t).sort(),r=new ur,a=[],i=["UNREACH_STICKY"],o=[hr.Types.info],l=[],h=[],_=[],u=[];n.forEach(m=>{var y,p,v;((y=t[m])==null?void 0:y.type)==="enum"?l.push(m):(v=(p=t[m])==null?void 0:p.common)!=null&&v.smartName&&u.push(m)}),l.forEach(m=>{m.startsWith("enum.rooms.")?h.push(m):m.startsWith("enum.functions.")&&_.push(m);const y=t[m].common.members;y!=null&&y.length&&y.forEach(p=>{t[p]&&(u.includes(p)||u.push(p))})});const g={id:"",objects:t,_keysOptional:n,_usedIdsOptional:a,ignoreIndicators:i,excludedTypes:o},d=[];u.forEach(m=>{g.id=m;const y=r.detect(g);y&&y.forEach(p=>{var me;const v=(me=p.states.find(N=>N.id))==null?void 0:me.id;if(!v||d.find(N=>N.id===v))return;const $=t[v],I={id:v,name:ye($.common.name,e),type:$.type,deviceType:p.type,states:p.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=v.split(".");let x,T;($.type==="channel"||$.type==="state")&&(F.pop(),x=F.join("."),t[x]&&(t[x].type==="channel"||t[x].type==="folder")?(F.pop(),T=F.join("."),(!t[T]||t[T].type!=="device"&&t[x].type!=="folder")&&(T=void 0)):x=void 0);const M=h.find(N=>{var ie,ve,Ce;return(ie=t[N].common.members)!=null&&ie.includes(v)||x&&((ve=t[N].common.members)!=null&&ve.includes(x))?!0:T&&((Ce=t[N].common.members)==null?void 0:Ce.includes(T))});M&&(I.room=ye(t[M].common.name,e));const se=_.find(N=>{var ie,ve,Ce;return(ie=t[N].common.members)!=null&&ie.includes(v)||x&&((ve=t[N].common.members)!=null&&ve.includes(x))?!0:T&&((Ce=t[N].common.members)==null?void 0:Ce.includes(T))});se&&(I.function=ye(t[se].common.name,e)),d.push(I)})});for(let m=0;m<d.length;m++){const y=d[m];if(y.type==="state"||y.type==="channel"){const p=y.id.split(".");p.pop();const v=t[p.join(".")];if(v&&(v.type==="channel"||v.type==="device"||v.type==="folder")){y.name=ye(((b=v.common)==null?void 0:b.name)||y.name,e),p.pop();const $=t[p.join(".")];($==null?void 0:$.type)==="device"&&((w=$.common)!=null&&w.icon)&&(y.name=ye(((A=$.common)==null?void 0:A.name)||y.name,e))}else y.name=ye(((E=v==null?void 0:v.common)==null?void 0:E.name)||y.name,e)}}return d}const va=async()=>(await Sa).default,Ca={ru:"Russian",en:"English",de:"German",es:"Spanish",fr:"French",it:"Italian",pl:"Polish",nl:"Dutch",pt:"Portuguese",uk:"Ukrainian","zh-cn":"Chinese"},qa=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),[h,_]=Z.useState(window.localStorage.getItem("openai-model")||"gpt-4o"),[u,g]=Z.useState(!1),d=Z.useRef(null),b=Z.useRef(null),w=Z.useRef(null),A=Z.useCallback(async()=>{var p;let E;d.current?E=d.current:(E=await Aa(s.socket),d.current=E,console.log(`devices: ${JSON.stringify(E,null,2)}`));let m;if(b.current)m=b.current;else{const v=Object.keys(s.runningInstances);for(let $=0;$<v.length;$++){const I=await s.socket.getObject(v[$]);if(m=((I==null?void 0:I.native.gptKey)||"").trim(),m)break}b.current=m||null}let y;if(w.current?y=w.current:(y=await va(),w.current=y),!m){g(!0);return}i(!0),l(!1);try{const I=(await new P({apiKey:m,dangerouslyAllowBrowser:!0}).chat.completions.create({model:h,messages:[{role:"system",content:`You are programmer. Here is a documentation:
22
+
23
+ ${y}`},{role:"system",content:`Here is list of devices:
24
+
25
+ ${JSON.stringify(E,null,2)}`},{role:"user",content:`Write JavaScript code that does:
26
+
27
+ ${e}
28
+ Return only code.
29
+ Write comments in ${Ca[U.I18n.getLanguage()]||"English"}.
30
+ 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.
31
+ Do not import any libraries as all functions are already imported.`}]})).choices[0].message,F=(p=I.content)==null?void 0:p.match(/```(javascript|js|typescript)\n?(.*)```(.*)/ms);let x;if(!F)x=I.content,x!=null&&x.startsWith("`")&&(x=x.substring(1)),x!=null&&x.endsWith("`")&&(x=x.substring(0,x.length-1));else if(x=F[2],F[3]){const T=F[3].split(`
32
+ `).map(M=>M.trim());for(;T[0]==="";)T.shift();x=`${T.map(M=>`// ${M}`).join(`
33
+ `)}
34
+ ${x}`}console.log(I),r(x||"")}catch(v){console.log(JSON.stringify(v)),v.error&&l(v.error.message),console.error(`Cannot request: ${v}, ${JSON.stringify(v.error||v,null,2)}`)}i(!1)},[e,h,s.runningInstances,s.socket]);return O.jsxs(j.Dialog,{maxWidth:"lg",sx:{"& .MuiDialog-paper":{height:"calc(100% - 100px)"}},open:!0,onClose:()=>s.onClose(),fullWidth:!0,children:[u&&O.jsxs(j.Dialog,{maxWidth:"lg",open:!0,onClose:()=>g(!1),fullWidth:!0,children:[O.jsx(j.DialogTitle,{children:U.I18n.t("No Chat GPT Key found")}),O.jsxs(j.DialogContent,{style:{display:"flex",flexDirection:"column",gap:8},children:[O.jsx("div",{children:U.I18n.t("You have to enter OpenAI API key in the configuration of javascript adapter.")}),O.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")})]}),O.jsx(j.DialogActions,{children:O.jsx(j.Button,{variant:"contained",startIcon:O.jsx(un,{}),onClick:()=>g(!1),children:U.I18n.t("Close")})})]}),O.jsx(j.DialogTitle,{children:U.I18n.t("AI code generator")}),O.jsxs(j.DialogContent,{style:{display:"flex",flexDirection:"column",gap:8,height:"100%"},children:[O.jsx("div",{children:O.jsx(j.TextField,{variant:"standard",multiline:!0,autoFocus:!0,disabled:a,fullWidth:!0,onKeyUp:E=>{E.key==="Enter"&&E.ctrlKey&&A()},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)}})}),O.jsxs("div",{style:{display:"flex",alignItems:"baseline"},children:[O.jsx(j.Button,{variant:"contained",disabled:a||!e,startIcon:O.jsx(fr,{}),onClick:async()=>A(),children:a?O.jsx(j.CircularProgress,{size:24}):U.I18n.t("Ask")}),O.jsxs(j.FormControl,{style:{width:150,marginLeft:20},variant:"standard",children:[O.jsx(j.InputLabel,{children:U.I18n.t("Model")}),O.jsxs(j.Select,{variant:"standard",value:h,onChange:E=>{window.localStorage.setItem("openai-model",E.target.value),o&&l(!1),_(E.target.value)},children:[O.jsx(j.MenuItem,{value:"gpt-4o",children:"GPT-4o"}),O.jsx(j.MenuItem,{value:"gpt-4-turbo",children:"GPT-4 Turbo"}),O.jsx(j.MenuItem,{value:"gpt-4-32k",children:"GPT-4 32k"}),O.jsx(j.MenuItem,{value:"gpt-4",children:"GPT-4"}),O.jsx(j.MenuItem,{value:"gpt-3.5-turbo-16k",children:"GPT-3.5 Turbo"})]})]})]}),O.jsx("div",{children:U.I18n.t("Result")}),O.jsx("div",{style:{height:"calc(100% - 155px)"},children:o?O.jsx("div",{style:{color:s.themeType==="dark"?"#984242":"#bb0000"},children:o}):O.jsx(dr,{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"})})]}),O.jsxs(j.DialogActions,{children:[O.jsx(j.Button,{color:"grey",variant:"outlined",disabled:!n,startIcon:O.jsx(cr,{}),onClick:()=>{U.Utils.copyToClipboard(n),window.alert(U.I18n.t("Copied"))},children:U.I18n.t("Copy to clipboard")}),O.jsx(j.Button,{color:"primary",variant:"contained",disabled:!n||o,startIcon:O.jsx(or,{}),onClick:()=>{s.onAddCode(n),s.onClose()},children:U.I18n.t("Use generated code")}),O.jsx(j.Button,{color:"grey",variant:"contained",startIcon:O.jsx(un,{}),onClick:()=>s.onClose(),children:U.I18n.t("Close")})]})]})};export{qa as default};
@@ -1 +1 @@
1
- import{c,j as s}from"./createSvgIcon-BQT-7-GS.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
+ import{c,j as s}from"./createSvgIcon-Dtl7HhPO.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-BQT-7-GS.js";import{R as i}from"./iobroker_javascript__loadShare__react__loadShare__-BiJPUKBK.js";import{i as r,I as n}from"./index-DnqHzUyv.js";import{i as a}from"./index-Cek-i92T.js";import l from"./ScriptEditorVanillaMonaco-DEgxOslR.js";import{I as c}from"./Save-BKC3BS3x.js";import"./_commonjsHelpers-Cpj98o6Y.js";import"./iobroker_javascript__mf_v__runtimeInit__mf_v__-CBQgOKij.js";import"./inheritsLoose--KnFDOw1.js";import"./preload-helper-Dp1pzeXC.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?`
1
+ import{j as e}from"./createSvgIcon-Dtl7HhPO.js";import{R as i}from"./iobroker_javascript__loadShare__react__loadShare__-BiJPUKBK.js";import{i as r,I as n}from"./index-C5V5CZI4.js";import{i as a}from"./index-DLBeMhRC.js";import l from"./ScriptEditorVanillaMonaco-D-2WOvcn.js";import{I as c}from"./Save-DgI3b32B.js";import"./_commonjsHelpers-Cpj98o6Y.js";import"./iobroker_javascript__mf_v__runtimeInit__mf_v__-CBQgOKij.js";import"./inheritsLoose-C9MZGDit.js";import"./preload-helper-Dp1pzeXC.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};
@@ -1 +1 @@
1
- import{j as n}from"./createSvgIcon-BQT-7-GS.js";import{R as S}from"./iobroker_javascript__loadShare__react__loadShare__-BiJPUKBK.js";import{i as p,o as b,aA as C}from"./index-DnqHzUyv.js";import{i as f}from"./index-Cek-i92T.js";import"./_commonjsHelpers-Cpj98o6Y.js";import"./iobroker_javascript__mf_v__runtimeInit__mf_v__-CBQgOKij.js";import"./inheritsLoose--KnFDOw1.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-Dtl7HhPO.js";import{R as S}from"./iobroker_javascript__loadShare__react__loadShare__-BiJPUKBK.js";import{i as p,o as b,aA as C}from"./index-C5V5CZI4.js";import{i as f}from"./index-DLBeMhRC.js";import"./_commonjsHelpers-Cpj98o6Y.js";import"./iobroker_javascript__mf_v__runtimeInit__mf_v__-CBQgOKij.js";import"./inheritsLoose-C9MZGDit.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};