iobroker.javascript 9.0.10 → 9.0.12

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 (132) hide show
  1. package/README.md +7 -10
  2. package/admin/assets/OpenAiDialog-Db5nBWtV.js +36 -0
  3. package/admin/assets/{Save--0ldNXLf.js → Save-DXaUpIPM.js} +1 -1
  4. package/admin/assets/{ScriptEditor-MKyboaPj.js → ScriptEditor-CuzI8bbK.js} +1 -1
  5. package/admin/assets/{ScriptEditorVanillaMonaco-CkDzb80s.js → ScriptEditorVanillaMonaco-LjlfPO8c.js} +1 -1
  6. package/admin/assets/{createSvgIcon-C_ElRFrf.js → createSvgIcon-DlIk-fDn.js} +3 -3
  7. package/admin/assets/hostInit-OBG53iVO.js +2 -0
  8. package/admin/assets/index-BCK6q-N6.css +1 -0
  9. package/admin/assets/{index-Dr_ZFwru.css → index-BTsjunTt.css} +1 -1
  10. package/admin/assets/{index-CMttI-gM.js → index-BWM5lJbO.js} +4 -4
  11. package/admin/assets/index-Cjl4b70e.js +5 -0
  12. package/admin/assets/{index-DmpUKunr.js → index-CpvUlHhu.js} +5 -5
  13. package/admin/assets/index-CtB5rga_.js +16 -0
  14. package/admin/assets/{index-BompUVvy.js → index-DoG44L1P.js} +1 -1
  15. package/admin/assets/index-DzAZ7TKU.js +1 -0
  16. package/admin/assets/index-XLsd8FZV.js +942 -0
  17. package/admin/assets/index-ee1BGSYh.js +1294 -0
  18. package/admin/assets/{inheritsLoose-CLw44UEv.js → inheritsLoose-DNrhibGS.js} +1 -1
  19. package/admin/assets/{iobroker_javascript__loadShare__react__loadShare__-B-pIv4x_.js → iobroker_javascript__loadShare__react__loadShare__-i8pXne9X.js} +1 -1
  20. package/admin/assets/iobroker_javascript__mf_v__runtimeInit__mf_v__-DZdFIfoQ.js +5 -0
  21. package/admin/assets/preload-helper-BDBacUwf.js +1 -0
  22. package/admin/assets/useTheme-DakN8Abq.js +1 -0
  23. package/admin/custom/assets/{Components-za_0yG9W.js → Components-DJLwk8Py.js} +1 -1
  24. package/admin/custom/assets/{ConfigCustomJavascriptSet__loadShare___mf_0_iobroker_mf_1_adapter_mf_2_react_mf_2_v5__loadShare__-BHJt30My.js → ConfigCustomJavascriptSet__loadShare___mf_0_iobroker_mf_1_adapter_mf_2_react_mf_2_v5__loadShare__-DaN0pfsw.js} +1 -1
  25. package/admin/custom/assets/{ConfigCustomJavascriptSet__loadShare___mf_0_mui_mf_1_material__loadShare__-WrqdT1Hz.js → ConfigCustomJavascriptSet__loadShare___mf_0_mui_mf_1_material__loadShare__-BqzgglHd.js} +1 -1
  26. package/admin/custom/assets/{ConfigCustomJavascriptSet__loadShare__react__loadShare__-B_YWmFeG.js → ConfigCustomJavascriptSet__loadShare__react__loadShare__-BNbscXK6.js} +1 -1
  27. package/admin/custom/assets/{ConfigCustomJavascriptSet__loadShare__react_mf_2_dom__loadShare__-DYzjQQsF.js → ConfigCustomJavascriptSet__loadShare__react_mf_2_dom__loadShare__-N2_tx_mJ.js} +1 -1
  28. package/admin/custom/assets/ConfigCustomJavascriptSet__mf_v__runtimeInit__mf_v__-jdUmHa_i.js +5 -0
  29. package/admin/custom/assets/DefaultPropsProvider-B6-0SEtV.js +7 -0
  30. package/admin/custom/assets/DefaultPropsProvider-BbFDEnmq.js +1 -0
  31. package/admin/custom/assets/{FilledInput-BGGUNS4j.js → FilledInput-CX9v1cwN.js} +2 -2
  32. package/admin/custom/assets/{Tabs-DjdFNknI.js → Tabs-bjxmjZcg.js} +6 -6
  33. package/admin/custom/assets/{ThemeProvider-Uan4kCQd.js → ThemeProvider-CeD4z8mE.js} +2 -2
  34. package/admin/custom/assets/_commonjsHelpers-CE1G-McA.js +1 -0
  35. package/admin/custom/assets/{createSvgIcon-BxCMHFh5.js → createSvgIcon-DAmSzHRD.js} +1 -1
  36. package/admin/custom/assets/{createTheme-Ajie0adn.js → createTheme-LEFpI6rM.js} +2 -2
  37. package/admin/custom/assets/defaultTheme-2suHr_rQ.js +1 -0
  38. package/admin/custom/assets/{hostInit-CrAs5YZS.js → hostInit-BJ6gSofk.js} +2 -2
  39. package/admin/custom/assets/{index-7YkEnLQM.js → index-1hRrucfm.js} +1 -1
  40. package/admin/custom/assets/{index-yiPj_-Rb.js → index-BM9YMTul.js} +1 -1
  41. package/admin/custom/assets/{index-Co3YA5NW.js → index-BgpTxVrG.js} +1 -1
  42. package/admin/custom/assets/index-CJimub3l.js +1399 -0
  43. package/admin/custom/assets/index-CPZpQ2Mb.js +916 -0
  44. package/admin/custom/assets/{index-UhQfKbTz.js → index-CrVgzaLe.js} +1 -1
  45. package/admin/custom/assets/{index-ClFSKKDu.js → index-CznMGPgM.js} +2 -2
  46. package/admin/custom/assets/{index-bxilEzdP.js → index-D-RbixT9.js} +5 -5
  47. package/admin/custom/assets/{index-DXg_kRe6.js → index-DMiiPxNM.js} +1 -1
  48. package/admin/custom/assets/{index-B2rBO0oC.js → index-DcK0RDrH.js} +1 -1
  49. package/admin/custom/assets/{index-DOnIDI_a.js → index-Dx7rDE4p.js} +1 -1
  50. package/admin/custom/assets/index-EogeheIH.js +31 -0
  51. package/admin/custom/assets/{jsx-runtime-lE4rOet2.js → jsx-runtime-CJ3ByJW3.js} +1 -1
  52. package/admin/custom/assets/leaflet-src-Dnh7srds.js +4 -0
  53. package/admin/custom/assets/preload-helper-BDBacUwf.js +1 -0
  54. package/admin/custom/assets/{useEnhancedEffect-DSK35Rma.js → useEnhancedEffect-COBJo-Ex.js} +2 -2
  55. package/admin/custom/assets/useTheme-52mADBCy.js +1 -0
  56. package/admin/custom/assets/{useTheme-DWmRkwMP.js → useTheme-Y8PztM11.js} +1 -1
  57. package/admin/custom/assets/virtualExposes-BMbgFEvP.js +2 -0
  58. package/admin/custom/customComponents.js +2 -2
  59. package/admin/i18n/de.json +1 -1
  60. package/admin/mf-manifest.json +1 -1
  61. package/admin/remoteEntry.js +2 -2
  62. package/admin/tab.html +10 -13
  63. package/build/lib/crypto.js +32 -0
  64. package/build/lib/crypto.js.map +1 -0
  65. package/{build-backend → build}/lib/javascript.d.ts +1507 -147
  66. package/{build-backend → build}/lib/protectFs.js +111 -104
  67. package/build/lib/protectFs.js.map +1 -0
  68. package/{build-backend → build}/lib/utils.js.map +1 -1
  69. package/{build-backend → build}/main.js +20 -12
  70. package/build/main.js.map +1 -0
  71. package/{build-backend → build}/types.d.ts +1 -0
  72. package/docs/en/javascript.md +1 -1
  73. package/io-package.json +26 -26
  74. package/package.json +22 -21
  75. package/admin/assets/OpenAiDialog-B4P-N63e.js +0 -36
  76. package/admin/assets/hostInit-fzxL8JAx.js +0 -2
  77. package/admin/assets/index-Bjydl5_6.js +0 -16
  78. package/admin/assets/index-DJdd5j6E.js +0 -930
  79. package/admin/assets/index-DUBaHZ92.css +0 -1
  80. package/admin/assets/index-DaagTm0N.js +0 -27
  81. package/admin/assets/index-DeFm7TiX.js +0 -5
  82. package/admin/assets/index-vw185EVR.js +0 -1294
  83. package/admin/assets/iobroker_javascript__mf_v__runtimeInit__mf_v__-CmuPLb0X.js +0 -5
  84. package/admin/assets/preload-helper-Dp1pzeXC.js +0 -1
  85. package/admin/assets/useTheme-CpAj0H76.js +0 -1
  86. package/admin/custom/assets/ConfigCustomJavascriptSet__mf_v__runtimeInit__mf_v__-Cib3-eWa.js +0 -5
  87. package/admin/custom/assets/DefaultPropsProvider-B41fRCEO.js +0 -1
  88. package/admin/custom/assets/DefaultPropsProvider-CfXkmG16.js +0 -7
  89. package/admin/custom/assets/_commonjsHelpers-D6-XlEtG.js +0 -1
  90. package/admin/custom/assets/defaultTheme-C_aSR-NR.js +0 -1
  91. package/admin/custom/assets/index-BkKMt4bp.js +0 -31
  92. package/admin/custom/assets/index-Bw5ZKbIF.js +0 -1399
  93. package/admin/custom/assets/index-K4NodPhU.js +0 -904
  94. package/admin/custom/assets/leaflet-src-A2ZHl6nF.js +0 -4
  95. package/admin/custom/assets/preload-helper-Dp1pzeXC.js +0 -1
  96. package/admin/custom/assets/useTheme-CpiJlUE9.js +0 -1
  97. package/admin/custom/assets/virtualExposes-4pgHXHfp.js +0 -2
  98. package/build-backend/lib/protectFs.js.map +0 -1
  99. package/build-backend/main.js.map +0 -1
  100. /package/{build-backend → build}/lib/consts.js +0 -0
  101. /package/{build-backend → build}/lib/consts.js.map +0 -0
  102. /package/{build-backend → build}/lib/convert.js +0 -0
  103. /package/{build-backend → build}/lib/convert.js.map +0 -0
  104. /package/{build-backend → build}/lib/debug.js +0 -0
  105. /package/{build-backend → build}/lib/debug.js.map +0 -0
  106. /package/{build-backend → build}/lib/debugger.js +0 -0
  107. /package/{build-backend → build}/lib/debugger.js.map +0 -0
  108. /package/{build-backend → build}/lib/eventObj.js +0 -0
  109. /package/{build-backend → build}/lib/eventObj.js.map +0 -0
  110. /package/{build-backend → build}/lib/inspect.js +0 -0
  111. /package/{build-backend → build}/lib/inspect.js.map +0 -0
  112. /package/{build-backend → build}/lib/mirror.js +0 -0
  113. /package/{build-backend → build}/lib/mirror.js.map +0 -0
  114. /package/{build-backend → build}/lib/nodeModulesManagement.js +0 -0
  115. /package/{build-backend → build}/lib/nodeModulesManagement.js.map +0 -0
  116. /package/{build-backend → build}/lib/patternCompareFunctions.js +0 -0
  117. /package/{build-backend → build}/lib/patternCompareFunctions.js.map +0 -0
  118. /package/{build-backend → build}/lib/request.js +0 -0
  119. /package/{build-backend → build}/lib/request.js.map +0 -0
  120. /package/{build-backend → build}/lib/sandbox.js +0 -0
  121. /package/{build-backend → build}/lib/sandbox.js.map +0 -0
  122. /package/{build-backend → build}/lib/scheduler.js +0 -0
  123. /package/{build-backend → build}/lib/scheduler.js.map +0 -0
  124. /package/{build-backend → build}/lib/tools.js +0 -0
  125. /package/{build-backend → build}/lib/tools.js.map +0 -0
  126. /package/{build-backend → build}/lib/typescriptSettings.js +0 -0
  127. /package/{build-backend → build}/lib/typescriptSettings.js.map +0 -0
  128. /package/{build-backend → build}/lib/typescriptTools.js +0 -0
  129. /package/{build-backend → build}/lib/typescriptTools.js.map +0 -0
  130. /package/{build-backend → build}/lib/utils.js +0 -0
  131. /package/{build-backend → build}/lib/words.js +0 -0
  132. /package/{build-backend → build}/lib/words.js.map +0 -0
package/io-package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "common": {
3
3
  "name": "javascript",
4
- "version": "9.0.10",
4
+ "version": "9.0.12",
5
5
  "blockedVersions": [
6
6
  "8.0.0",
7
7
  "8.0.1"
@@ -40,18 +40,31 @@
40
40
  "Matthias Kleine <info@haus-automatisierung.com>"
41
41
  ],
42
42
  "news": {
43
- "9.0.10": {
44
- "en": "Added Blockly block to format a numeric value\nFixing some blocks in blockly: cron, time\nAdded new block: \"unconditional return\"\nType definitions for TypeScript were updated\nCorrected bug with deleting of sub-folders",
45
- "de": "Hinzugefügt Blockly Block, um einen numerischen Wert zu formatieren\nEinige Blöcke blockweise fixieren: cron, time\nNeuer Block hinzugefügt: \"bedingungslose Rückkehr\"\nTypdefinitionen für TypeScript wurden aktualisiert\nFehler behoben mit Löschen von Unterordner",
46
- "ru": "Добавлен блок Blockly для форматирования числового значения\nПочинка блоков в блоке: крон, время\nДобавлен новый блок: \"безусловный возврат\"\nОбновлены определения типов для TypeScript\nИсправлена ошибка с удалением подпапок",
47
- "pt": "Adicionado Bloco para formatar um valor numérico\nConsertando alguns blocos em bloco: cron, tempo\nAdicionado novo bloco: \"retorno incondicional\"\nAs definições de tipo para TypeScript foram atualizadas\nErro corrigido com a exclusão de subpastas",
48
- "nl": "Blockly blok toegevoegd om een numerieke waarde te formatteren\nHet repareren van wat blokken in blokjes: cron, tijd\nToegevoegd nieuw blok: \"onvoorwaardelijke terugkeer\"\nTypedefinities voor TypeScript zijn bijgewerkt\nGecorrigeerde bug met verwijderen van submappen",
49
- "fr": "Ajout d'un bloc bloc bloc pour formater une valeur numérique\nCorrection de quelques blocs en bloc : cron, temps\nAjout d'un nouveau bloc : « retour inconditionnel »\nLes définitions de type pour TypeScript ont été mises à jour\nCorrection du bogue avec suppression des sous-dossiers",
50
- "it": "Aggiunto Blockly per formattare un valore numerico\nFissare alcuni blocchi in blocco: cron, tempo\nAggiunto nuovo blocco: \"ritorno incondizionato\"\nLe definizioni di tipo per TypeScript sono state aggiornate\nCorretto bug con cancellazione di sotto-cartelle",
51
- "es": "Añadido Bloqueo bloqueado para formatear un valor numérico\nArreglar algunos bloques en bloque: cron, tiempo\nNuevo bloque añadido: \"retorno incondicional\"\nSe actualizaron las definiciones de tipo para TipoScript\nError corregido con eliminación de subcarpetas",
52
- "pl": "Dodano Blockly bloku do formatu wartości liczbowej\nNaprawianie niektórych bloków w blokowanych: cron, czas\nDodano nowy blok: \"bezwarunkowy powrót\"\nDefinicje typu dla TypeScript zostały zaktualizowane\nPoprawiony błąd z usuwaniem podfolderów",
53
- "uk": "Додано блокнот для форматування числового значення\nВиправлення деяких блоків в блокноті: cron, час\nДодано новий блок: \"безумовне повернення\"\nОновлено тип визначення для TypeScript\nВиправлена помилка з видаленням підпапок",
54
- "zh-cn": "添加块格式化一个数值\n整顿一些街区: cron, time\n新增块:\"无条件返回\"\n更新了 TypeScript 的类型定义\n删除子文件夹纠正错误"
43
+ "9.0.12": {
44
+ "en": "Added possibility to encrypt scripts with password (only for vendors)",
45
+ "de": "Zusätzliche Möglichkeit, Skripte mit Passwort zu verschlüsseln (nur für Hersteller)",
46
+ "ru": "Добавлена возможность шифрования скриптов с помощью пароля (только для продавцов)",
47
+ "pt": "Adicionada possibilidade de criptografar scripts com senha (somente para fornecedores)",
48
+ "nl": "Toegevoegd mogelijkheid om scripts te versleutelen met wachtwoord (alleen voor leveranciers)",
49
+ "fr": "Ajout de la possibilité de chiffrer les scripts avec le mot de passe (seulement pour les fournisseurs)",
50
+ "it": "Aggiunta possibilità di crittografare gli script con password (solo per i fornitori)",
51
+ "es": "Añadido posibilidad de cifrar scripts con contraseña (sólo para proveedores)",
52
+ "pl": "Dodano możliwość szyfrowania skryptów hasłem (tylko dla sprzedawców)",
53
+ "uk": "Додана можливість шифрування сценаріїв з паролем (тільки для постачальників)",
54
+ "zh-cn": "添加使用密码加密脚本的可能性( 只针对供应商)"
55
+ },
56
+ "9.0.11": {
57
+ "en": "Corrected the rule editor if the condition is empty\nCorrected types for TypeScript",
58
+ "de": "Korrektur des Regeleditors, wenn die Bedingung leer ist\nKorrigierte Typen für TypeScript",
59
+ "ru": "Исправлен редактор правил, если условие пусто\nИсправленные типы для TypeScript",
60
+ "pt": "Corrigido o editor de regras se a condição estiver vazia\nTipos corrigidos para TypeScript",
61
+ "nl": "De regelbewerker corrigeren als de voorwaarde leeg is\nGecorrigeerde types voor TypeScript",
62
+ "fr": "Correction de l'éditeur de règles si la condition est vide\nTypes corrigés pour TypeScript",
63
+ "it": "Corretto l'editor di regola se la condizione è vuota\nTipi corretti per TypeScript",
64
+ "es": "Corregido el editor de reglas si la condición está vacía\nTipos corregidos para TipoScript",
65
+ "pl": "Poprawiono edytor zasad, jeśli warunek jest pusty\nPoprawione typy dla TypeScript",
66
+ "uk": "Виправлено редактор правила, якщо стан порожній\nВиправлені типи для TypeScript",
67
+ "zh-cn": "如果条件为空, 更正规则编辑器\n类型脚本的校正类型"
55
68
  },
56
69
  "9.0.7": {
57
70
  "en": "Fixing some blocks in blockly: time, function",
@@ -117,19 +130,6 @@
117
130
  "pl": "Poprawiono edytor zasad\nUsunięto niewykorzystane pliki JS",
118
131
  "uk": "Виправлено редактор правила\nВидалити невикористані файли JS",
119
132
  "zh-cn": "更正规则编辑器\n删除未使用的 JS 文件"
120
- },
121
- "9.0.2": {
122
- "en": "Added possibility to escape chars in formatTimeDiff\nBack-end was migrated to TypeScript\nBreaking change: removed \"request\" module\nAdded prettier for scripts",
123
- "de": "Zusätzliche Möglichkeit, Zeichen im Format zu entkommen TimeDiff\nBackend wurde zu TypeScript migriert\nBreaking change: entferntes Modul \"Request\"\nHinzugefügt schöner für Scripts",
124
- "ru": "Добавлена возможность побега чаров в формате тайм-дифф\nBack-end был перенесен на TypeScript\nПереломное изменение: удален модуль «запрос»\nДобавлено красивее для сценариев",
125
- "pt": "Adicionado possibilidade de escapar de chars em formato Ponto de vista\nO back-end foi migrado para TypeScript\nAlteração de ruptura: módulo de \"requisição\" removido\nAdicionado mais bonito para scripts",
126
- "nl": "Toegevoegd mogelijkheid om te ontsnappen tekens in formaat TimeDiff\nBack-end is gemigreerd naar TypeScript\nBreaking change: verwijderd \"verzoek\" module\nMooier toegevoegd voor scripts",
127
- "fr": "Ajout de la possibilité d'échapper aux caractères dans le format TimeDiff\nBack-end a été migré vers TypeScript\nChangement de rupture: supprimé module \"demande\"\nAjout de joli pour les scripts",
128
- "it": "Aggiunta possibilità di sfuggire a chars in formato Orario\nBack-end è stato migrato a TypeScript\nCambiamento di rottura: rimosso modulo \"richiesta\"\nAggiunto più bello per gli script",
129
- "es": "Añadido posibilidad de escapar de los charcos en formato TimeDiff\nBack-end fue migrado a TipoScript\nCambio de ruptura: módulo de \"requisición\" eliminado\nAñadido más alto para scripts",
130
- "pl": "Dodano możliwość ucieczki znaków w formacie TimeDiff\nBack- end został przeniesiony do TypeScript\nZmiana: usunięty moduł \"request\"\nDodano ładniejsze dla skryptów",
131
- "uk": "Додано можливість втекти chars у форматі Час\nBack-end був мігрований до TypeScript\nЗміна несправностей: видалений модуль \"запит\"\nДодано претtier для скриптів",
132
- "zh-cn": "添加格式跳过字符的可能性 时间\n后端已迁移到类型脚本\n中断更改: 删除“ 请求” 模块\n为脚本添加更美的"
133
133
  }
134
134
  },
135
135
  "platform": "Javascript/Node.js",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "iobroker.javascript",
3
- "version": "9.0.10",
3
+ "version": "9.0.12",
4
4
  "description": "Rules Engine for ioBroker",
5
5
  "author": "bluefox <dogafox@gmail.com>",
6
6
  "contributors": [
@@ -41,35 +41,35 @@
41
41
  "@types/node": "should match the lowest MAJOR version of Node.js we support."
42
42
  },
43
43
  "dependencies": {
44
- "@iobroker/adapter-core": "^3.2.3",
44
+ "@iobroker/adapter-core": "^3.3.2",
45
45
  "@iobroker/types": "^7.0.7",
46
- "@types/node": "^24.0.8",
47
- "axios": "^1.10.0",
48
- "jsonata": "^2.0.6",
46
+ "@types/node": "^24.9.2",
47
+ "axios": "^1.13.2",
48
+ "jsonata": "^2.1.0",
49
49
  "jszip": "^3.10.1",
50
50
  "node-inspect": "^2.0.0",
51
51
  "node-schedule": "2.1.1",
52
- "prettier": "^3.5.3",
52
+ "prettier": "^3.6.2",
53
53
  "promisify-child-process": "^4.1.2",
54
- "semver": "^7.7.2",
54
+ "semver": "^7.7.3",
55
55
  "suncalc2": "^1.8.1",
56
56
  "typescript": "~5.8.3",
57
57
  "virtual-tsc": "^0.6.2",
58
58
  "wake_on_lan": "^1.0.0"
59
59
  },
60
60
  "devDependencies": {
61
- "@alcalzone/release-script": "^3.8.0",
62
- "@alcalzone/release-script-plugin-iobroker": "^3.7.2",
63
- "@alcalzone/release-script-plugin-license": "^3.7.0",
64
- "@iobroker/adapter-dev": "^1.4.0",
61
+ "@alcalzone/release-script": "^5.0.0",
62
+ "@alcalzone/release-script-plugin-iobroker": "^4.0.0",
63
+ "@alcalzone/release-script-plugin-license": "^4.0.0",
64
+ "@iobroker/adapter-dev": "^1.5.0",
65
65
  "@iobroker/build-tools": "^2.0.15",
66
- "@iobroker/eslint-config": "^2.0.2",
67
- "@iobroker/plugin-sentry": "^2.0.4",
68
- "@iobroker/testing": "^5.0.4",
66
+ "@iobroker/eslint-config": "^2.2.0",
67
+ "@iobroker/plugin-sentry": "^3.0.0",
68
+ "@iobroker/testing": "^5.2.2",
69
69
  "@iobroker/vis-2-widgets-react-dev": "^4.0.4",
70
- "@types/node-schedule": "^2.1.7",
71
- "@types/nodemailer": "^6.4.17",
72
- "@types/request": "^2.48.12",
70
+ "@types/node-schedule": "^2.1.8",
71
+ "@types/nodemailer": "^7.0.4",
72
+ "@types/request": "^2.48.13",
73
73
  "@types/suncalc": "^1.9.2",
74
74
  "alcalzone-shared": "^5.0.0",
75
75
  "timekeeper": "^2.3.1"
@@ -77,10 +77,10 @@
77
77
  "bugs": {
78
78
  "url": "https://github.com/ioBroker/ioBroker.javascript/issues"
79
79
  },
80
- "main": "build-backend/main.js",
80
+ "main": "build/main.js",
81
81
  "files": [
82
82
  "admin/",
83
- "build-backend/",
83
+ "build/",
84
84
  "docs/",
85
85
  "install/",
86
86
  "io-package.json",
@@ -89,12 +89,13 @@
89
89
  ],
90
90
  "scripts": {
91
91
  "test:declarations": "tsc -p test/lib/TS/tsconfig.json && tsc -p test/lib/JS/tsconfig.json",
92
- "test:javascript": "node node_modules/mocha/bin/mocha --exit",
92
+ "test:javascript": "mocha --exit",
93
+ "test:scheduler": "mocha test/testScheduler.js --exit",
93
94
  "test": "npm run test:declarations && npm run test:javascript",
94
95
  "translate": "translate-adapter",
95
96
  "//postinstall": "node ./install/installTypings.js",
96
97
  "build": "npm run build-backend && node tasks",
97
- "build-backend": "tsc -p tsconfig.build.json",
98
+ "build-backend": "tsc -p tsconfig.build.json && node tasks --copy-types",
98
99
  "release": "release-script --noPush -y --all",
99
100
  "update-packages": "npx -y npm-check-updates --upgrade && cd src-editor && npx -y npm-check-updates --upgrade && cd ../src-admin && npx -y npm-check-updates --upgrade",
100
101
  "npm": "npm i && cd src-editor && npm i -f && cd ../src-admin && npm i",
@@ -1,36 +0,0 @@
1
- import{c as cr,j as E}from"./createSvgIcon-C_ElRFrf.js";import{i as Z}from"./iobroker_javascript__loadShare__react__loadShare__-B-pIv4x_.js";import{i as j,c as hn,C as lr}from"./index-DeFm7TiX.js";import{i as U,h as ur}from"./index-vw185EVR.js";import{_ as hr}from"./preload-helper-Dp1pzeXC.js";import{C as dr,t as fr}from"./index-BompUVvy.js";import mr from"./ScriptEditorVanillaMonaco-CkDzb80s.js";import"./_commonjsHelpers-Cpj98o6Y.js";import"./iobroker_javascript__mf_v__runtimeInit__mf_v__-CmuPLb0X.js";import"./inheritsLoose-CLw44UEv.js";const pr=cr(E.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 C(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 o(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 Dn=function(){const{crypto:s}=globalThis;if(s!=null&&s.randomUUID)return Dn=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 Ot(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 I extends Error{}class H extends I{constructor(e,t,n,r){super(`${H.makeMessage(e,t,n)}`),this.status=e,this.headers=r,this.requestID=r==null?void 0:r.get("x-request-id"),this.error=t;const a=t;this.code=a==null?void 0:a.code,this.param=a==null?void 0:a.param,this.type=a==null?void 0:a.type}static makeMessage(e,t,n){const r=t!=null&&t.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&r?`${e} ${r}`:e?`${e} status code (no body)`:r||"(no status code or body)"}static generate(e,t,n,r){if(!e||!r)return new mt({message:n,cause:Et(t)});const a=t==null?void 0:t.error;return e===400?new Bn(e,a,n,r):e===401?new Wn(e,a,n,r):e===403?new Un(e,a,n,r):e===404?new qn(e,a,n,r):e===409?new Jn(e,a,n,r):e===422?new Hn(e,a,n,r):e===429?new Xn(e,a,n,r):e>=500?new Kn(e,a,n,r):new H(e,a,n,r)}}class z extends H{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class mt extends H{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}}class qt extends mt{constructor({message:e}={}){super({message:e??"Request timed out."})}}class Bn extends H{}class Wn extends H{}class Un extends H{}class qn extends H{}class Jn extends H{}class Hn extends H{}class Xn extends H{}class Kn extends H{}class Vn extends I{constructor(){super("Could not parse response content as the length limit was reached")}}class Gn extends I{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class Re extends Error{constructor(e){super(e)}}const gr=/^[a-z][a-z0-9+.-]*:/i,_r=s=>gr.test(s);let K=s=>(K=Array.isArray,K(s)),dn=K;function yr(s){return typeof s!="object"?{}:s??{}}function wr(s){if(!s)return!0;for(const e in s)return!1;return!0}function br(s,e){return Object.prototype.hasOwnProperty.call(s,e)}function St(s){return s!=null&&typeof s=="object"&&!Array.isArray(s)}const Sr=(s,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new I(`${s} must be an integer`);if(e<0)throw new I(`${s} must be a positive integer`);return e},xr=s=>{try{return JSON.parse(s)}catch{return}},Be=s=>new Promise(e=>setTimeout(e,s)),we="5.10.2",Ar=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function vr(){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 Cr=()=>{var t;const s=vr();if(s==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":we,"X-Stainless-OS":mn(Deno.build.os),"X-Stainless-Arch":fn(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":mn(globalThis.process.platform??"unknown"),"X-Stainless-Arch":fn(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const e=Ir();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 Ir(){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 fn=s=>s==="x32"?"x32":s==="x86_64"||s==="x64"?"x64":s==="arm"?"arm":s==="aarch64"||s==="arm64"?"arm64":s?`other:${s}`:"unknown",mn=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 pn;const Rr=()=>pn??(pn=Cr());function kr(){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 Qn(...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 zn(s){let e=Symbol.asyncIterator in s?s[Symbol.asyncIterator]():s[Symbol.iterator]();return Qn({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 Yn(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 $r(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 Or=({headers:s,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)}),Zn="RFC3986",es=s=>String(s),gn={RFC1738:s=>String(s).replace(/%20/g,"+"),RFC3986:es},Er="RFC1738";let Pt=(s,e)=>(Pt=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Pt(s,e));const ee=(()=>{const s=[];for(let e=0;e<256;++e)s.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return s})(),xt=1024,Pr=(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(c){return"%26%23"+parseInt(c.slice(2),16)+"%3B"});let i="";for(let c=0;c<a.length;c+=xt){const l=a.length>=xt?a.slice(c,c+xt):a,u=[];for(let m=0;m<l.length;++m){let h=l.charCodeAt(m);if(h===45||h===46||h===95||h===126||h>=48&&h<=57||h>=65&&h<=90||h>=97&&h<=122||r===Er&&(h===40||h===41)){u[u.length]=l.charAt(m);continue}if(h<128){u[u.length]=ee[h];continue}if(h<2048){u[u.length]=ee[192|h>>6]+ee[128|h&63];continue}if(h<55296||h>=57344){u[u.length]=ee[224|h>>12]+ee[128|h>>6&63]+ee[128|h&63];continue}m+=1,h=65536+((h&1023)<<10|l.charCodeAt(m)&1023),u[u.length]=ee[240|h>>18]+ee[128|h>>12&63]+ee[128|h>>6&63]+ee[128|h&63]}i+=u.join("")}return i};function Tr(s){return!s||typeof s!="object"?!1:!!(s.constructor&&s.constructor.isBuffer&&s.constructor.isBuffer(s))}function _n(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 ts={brackets(s){return String(s)+"[]"},comma:"comma",indices(s,e){return String(s)+"["+e+"]"},repeat(s){return String(s)}},ns=function(s,e){Array.prototype.push.apply(s,K(e)?e:[e])};let yn;const B={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Pr,encodeValuesOnly:!1,format:Zn,formatter:es,indices:!1,serializeDate(s){return(yn??(yn=Function.prototype.call.bind(Date.prototype.toISOString)))(s)},skipNulls:!1,strictNullHandling:!1};function Mr(s){return typeof s=="string"||typeof s=="number"||typeof s=="boolean"||typeof s=="symbol"||typeof s=="bigint"}const At={};function ss(s,e,t,n,r,a,i,c,l,u,m,h,g,d,b,w,A,O){let p=s,y=O,_=0,v=!1;for(;(y=y.get(At))!==void 0&&!v;){const T=y.get(s);if(_+=1,typeof T<"u"){if(T===_)throw new RangeError("Cyclic object value");v=!0}typeof y.get(At)>"u"&&(_=0)}if(typeof u=="function"?p=u(e,p):p instanceof Date?p=g==null?void 0:g(p):t==="comma"&&K(p)&&(p=_n(p,function(T){return T instanceof Date?g==null?void 0:g(T):T})),p===null){if(a)return l&&!w?l(e,B.encoder,A,"key",d):e;p=""}if(Mr(p)||Tr(p)){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(p,B.encoder,A,"value",d)))]}return[(b==null?void 0:b(e))+"="+(b==null?void 0:b(String(p)))]}const $=[];if(typeof p>"u")return $;let R;if(t==="comma"&&K(p))w&&l&&(p=_n(p,l)),R=[{value:p.length>0?p.join(",")||null:void 0}];else if(K(u))R=u;else{const T=Object.keys(p);R=m?T.sort(m):T}const F=c?String(e).replace(/\./g,"%2E"):String(e),x=n&&K(p)&&p.length===1?F+"[]":F;if(r&&K(p)&&p.length===0)return x+"[]";for(let T=0;T<R.length;++T){const M=R[T],se=typeof M=="object"&&typeof M.value<"u"?M.value:p[M];if(i&&se===null)continue;const me=h&&c?M.replace(/\./g,"%2E"):M,N=K(p)?typeof t=="function"?t(x,me):x:x+(h?"."+me:"["+me+"]");O.set(s,_);const ie=new WeakMap;ie.set(At,O),ns($,ss(se,N,t,n,r,a,i,c,t==="comma"&&w&&K(p)?null:l,u,m,h,g,d,b,w,A,ie))}return $}function Nr(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(!Pt(gn,s.format))throw new TypeError("Unknown format option provided.");t=s.format}const n=gn[t];let r=B.filter;(typeof s.filter=="function"||K(s.filter))&&(r=s.filter);let a;if(s.arrayFormat&&s.arrayFormat in ts?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 jr(s,e={}){let t=s;const n=Nr(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 c=ts[n.arrayFormat],l=c==="comma"&&n.commaRoundTrip;r||(r=Object.keys(t)),n.sort&&r.sort(n.sort);const u=new WeakMap;for(let g=0;g<r.length;++g){const d=r[g];n.skipNulls&&t[d]===null||ns(i,ss(t[d],d,c,l,n.allowEmptyArrays,n.strictNullHandling,n.skipNulls,n.encodeDotInKeys,n.encode?n.encoder:null,n.filter,n.sort,n.allowDots,n.serializeDate,n.format,n.formatter,n.encodeValuesOnly,n.charset,u))}const m=i.join(n.delimiter);let h=n.addQueryPrefix===!0?"?":"";return n.charsetSentinel&&(n.charset==="iso-8859-1"?h+="utf8=%26%2310003%3B&":h+="utf8=%E2%9C%93&"),m.length>0?h+m:""}function Fr(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 wn;function Jt(s){let e;return(wn??(e=new globalThis.TextEncoder,wn=e.encode.bind(e)))(s)}let bn;function Sn(s){let e;return(bn??(e=new globalThis.TextDecoder,bn=e.decode.bind(e)))(s)}var V,G;class pt{constructor(){V.set(this,void 0),G.set(this,void 0),C(this,V,new Uint8Array),C(this,G,null)}decode(e){if(e==null)return[];const t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?Jt(e):e;C(this,V,Fr([o(this,V,"f"),t]));const n=[];let r;for(;(r=Lr(o(this,V,"f"),o(this,G,"f")))!=null;){if(r.carriage&&o(this,G,"f")==null){C(this,G,r.index);continue}if(o(this,G,"f")!=null&&(r.index!==o(this,G,"f")+1||r.carriage)){n.push(Sn(o(this,V,"f").subarray(0,o(this,G,"f")-1))),C(this,V,o(this,V,"f").subarray(o(this,G,"f"))),C(this,G,null);continue}const a=o(this,G,"f")!==null?r.preceding-1:r.preceding,i=Sn(o(this,V,"f").subarray(0,a));n.push(i),C(this,V,o(this,V,"f").subarray(r.index)),C(this,G,null)}return n}flush(){return o(this,V,"f").length?this.decode(`
2
- `):[]}}V=new WeakMap,G=new WeakMap;pt.NEWLINE_CHARS=new Set([`
3
- `,"\r"]);pt.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Lr(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 Dr(s){for(let n=0;n<s.length-1;n++){if(s[n]===10&&s[n+1]===10||s[n]===13&&s[n+1]===13)return n+2;if(s[n]===13&&s[n+1]===10&&n+3<s.length&&s[n+2]===13&&s[n+3]===10)return n+4}return-1}const ot={off:0,error:200,warn:300,info:400,debug:500},xn=(s,e,t)=>{if(s){if(br(ot,s))return s;q(t).warn(`${e} was set to ${JSON.stringify(s)}, expected one of ${JSON.stringify(Object.keys(ot))}`)}};function ke(){}function Je(s,e,t){return!e||ot[s]>ot[t]?ke:e[s].bind(e)}const Br={error:ke,warn:ke,info:ke,debug:ke};let An=new WeakMap;function q(s){const e=s.logger,t=s.logLevel??"off";if(!e)return Br;const n=An.get(e);if(n&&n[0]===t)return n[1];const r={error:Je("error",e,t),warn:Je("warn",e,t),info:Je("info",e,t),debug:Je("debug",e,t)};return An.set(e,[t,r]),r}const le=s=>(s.options&&(s.options={...s.options},delete s.options.headers),s.headers&&(s.headers=Object.fromEntries((s.headers instanceof Headers?[...s.headers]:Object.entries(s.headers)).map(([e,t])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":t]))),"retryOfRequestLogID"in s&&(s.retryOfRequestLogID&&(s.retryOf=s.retryOfRequestLogID),delete s.retryOfRequestLogID),s);var Ie;class ne{constructor(e,t,n){this.iterator=e,Ie.set(this,void 0),this.controller=t,C(this,Ie,n)}static fromSSEResponse(e,t,n){let r=!1;const a=n?q(n):console;async function*i(){if(r)throw new I("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let c=!1;try{for await(const l of Wr(e,t))if(!c){if(l.data.startsWith("[DONE]")){c=!0;continue}if(l.event===null||l.event.startsWith("response.")||l.event.startsWith("image_edit.")||l.event.startsWith("image_generation.")||l.event.startsWith("transcript.")){let u;try{u=JSON.parse(l.data)}catch(m){throw a.error("Could not parse message into JSON:",l.data),a.error("From chunk:",l.raw),m}if(u&&u.error)throw new H(void 0,u.error,void 0,e.headers);yield u}else{let u;try{u=JSON.parse(l.data)}catch(m){throw console.error("Could not parse message into JSON:",l.data),console.error("From chunk:",l.raw),m}if(l.event=="error")throw new H(void 0,u.error,u.message,void 0);yield{event:l.event,data:u}}}c=!0}catch(l){if(Ot(l))return;throw l}finally{c||t.abort()}}return new ne(i,t,n)}static fromReadableStream(e,t,n){let r=!1;async function*a(){const c=new pt,l=Yn(e);for await(const u of l)for(const m of c.decode(u))yield m;for(const u of c.flush())yield u}async function*i(){if(r)throw new I("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let c=!1;try{for await(const l of a())c||l&&(yield JSON.parse(l));c=!0}catch(l){if(Ot(l))return;throw l}finally{c||t.abort()}}return new ne(i,t,n)}[(Ie=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){const e=[],t=[],n=this.iterator(),r=a=>({next:()=>{if(a.length===0){const i=n.next();e.push(i),t.push(i)}return a.shift()}});return[new ne(()=>r(e),this.controller,o(this,Ie,"f")),new ne(()=>r(t),this.controller,o(this,Ie,"f"))]}toReadableStream(){const e=this;let t;return Qn({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=Jt(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*Wr(s,e){if(!s.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new I("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 I("Attempted to iterate over a response with no body");const t=new qr,n=new pt,r=Yn(s.body);for await(const a of Ur(r))for(const i of n.decode(a)){const c=t.decode(i);c&&(yield c)}for(const a of n.flush()){const i=t.decode(a);i&&(yield i)}}async function*Ur(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"?Jt(t):t;let r=new Uint8Array(e.length+n.length);r.set(e),r.set(n,e.length),e=r;let a;for(;(a=Dr(e))!==-1;)yield e.slice(0,a),e=e.slice(a)}e.length>0&&(yield e)}class qr{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]=Jr(e,":");return r.startsWith(" ")&&(r=r.substring(1)),t==="event"?this.event=r:t==="data"&&this.data.push(r),null}}function Jr(s,e){const t=s.indexOf(e);return t!==-1?[s.substring(0,t),e,s.substring(t+e.length)]:[s,"",""]}async function rs(s,e){const{response:t,requestLogID:n,retryOfRequestLogID:r,startTime:a}=e,i=await(async()=>{var h;if(e.options.stream)return q(s).debug("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller,s):ne.fromSSEResponse(t,e.controller,s);if(t.status===204)return null;if(e.options.__binaryResponse)return t;const c=t.headers.get("content-type"),l=(h=c==null?void 0:c.split(";")[0])==null?void 0:h.trim();if((l==null?void 0:l.includes("application/json"))||(l==null?void 0:l.endsWith("+json"))){const g=await t.json();return as(g,t)}return await t.text()})();return q(s).debug(`[${n}] response parsed`,le({retryOfRequestLogID:r,url:t.url,status:t.status,body:i,durationMs:Date.now()-a})),i}function as(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 $e;class gt extends Promise{constructor(e,t,n=rs){super(r=>{r(null)}),this.responsePromise=t,this.parseResponse=n,$e.set(this,void 0),C(this,$e,e)}_thenUnwrap(e){return new gt(o(this,$e,"f"),this.responsePromise,async(t,n)=>as(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(o(this,$e,"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)}}$e=new WeakMap;var He;class is{constructor(e,t,n,r){He.set(this,void 0),C(this,He,e),this.options=r,this.response=t,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){const e=this.nextPageRequestOptions();if(!e)throw new I("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await o(this,He,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(He=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}}class Hr extends gt{constructor(e,t,n){super(e,t,async(r,a)=>new n(r,a.response,await rs(r,a),a.options))}async*[Symbol.asyncIterator](){const e=await this;for await(const t of e)yield t}}class _t extends is{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 is{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:{...yr(this.options.query),after:t}}:null}}const os=()=>{var s;if(typeof File>"u"){const{process:e}=globalThis,t=typeof((s=e==null?void 0:e.versions)==null?void 0:s.node)=="string"&&parseInt(e.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(t?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function je(s,e,t){return os(),new File(s,e??"unknown_file",t)}function Ye(s){return(typeof s=="object"&&s!==null&&("name"in s&&s.name&&String(s.name)||"url"in s&&s.url&&String(s.url)||"filename"in s&&s.filename&&String(s.filename)||"path"in s&&s.path&&String(s.path))||"").split(/[\\/]/).pop()||void 0}const cs=s=>s!=null&&typeof s=="object"&&typeof s[Symbol.asyncIterator]=="function",fe=async(s,e)=>({...s,body:await Kr(s.body,e)}),vn=new WeakMap;function Xr(s){const e=typeof s=="function"?s:s.fetch,t=vn.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 vn.set(e,n),n}const Kr=async(s,e)=>{if(!await Xr(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])=>Tt(t,n,r))),t},Vr=s=>s instanceof Blob&&"name"in s,Tt=async(s,e,t)=>{if(t!==void 0){if(t==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")s.append(e,String(t));else if(t instanceof Response)s.append(e,je([await t.blob()],Ye(t)));else if(cs(t))s.append(e,je([await new Response(zn(t)).blob()],Ye(t)));else if(Vr(t))s.append(e,t,Ye(t));else if(Array.isArray(t))await Promise.all(t.map(n=>Tt(s,e+"[]",n)));else if(typeof t=="object")await Promise.all(Object.entries(t).map(([n,r])=>Tt(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`)}},ls=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",Gr=s=>s!=null&&typeof s=="object"&&typeof s.name=="string"&&typeof s.lastModified=="number"&&ls(s),Qr=s=>s!=null&&typeof s=="object"&&typeof s.url=="string"&&typeof s.blob=="function";async function zr(s,e,t){if(os(),s=await s,Gr(s))return s instanceof File?s:je([await s.arrayBuffer()],s.name);if(Qr(s)){const r=await s.blob();return e||(e=new URL(s.url).pathname.split(/[\\/]/).pop()),je(await Mt(r),e,t)}const n=await Mt(s);if(e||(e=Ye(s)),!(t!=null&&t.type)){const r=n.find(a=>typeof a=="object"&&"type"in a&&a.type);typeof r=="string"&&(t={...t,type:r})}return je(n,e,t)}async function Mt(s){var t;let e=[];if(typeof s=="string"||ArrayBuffer.isView(s)||s instanceof ArrayBuffer)e.push(s);else if(ls(s))e.push(s instanceof Blob?s:await s.arrayBuffer());else if(cs(s))for await(const n of s)e.push(...await Mt(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}`:""}${Yr(s)}`)}return e}function Yr(s){return typeof s!="object"||s===null?"":`; props: [${Object.getOwnPropertyNames(s).map(t=>`"${t}"`).join(", ")}]`}class k{constructor(e){this._client=e}}function us(s){return s.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const Cn=Object.freeze(Object.create(null)),Zr=(s=us)=>function(t,...n){if(t.length===1)return t[0];let r=!1;const a=[],i=t.reduce((m,h,g)=>{var w;/[?#]/.test(h)&&(r=!0);const d=n[g];let b=(r?encodeURIComponent:s)(""+d);return g!==n.length&&(d==null||typeof d=="object"&&d.toString===((w=Object.getPrototypeOf(Object.getPrototypeOf(d.hasOwnProperty??Cn)??Cn))==null?void 0:w.toString))&&(b=d+"",a.push({start:m.length+h.length,length:b.length,error:`Value of type ${Object.prototype.toString.call(d).slice(8,-1)} is not a valid path parameter`})),m+h+(g===n.length?"":b)},""),c=i.split(/[?#]/,1)[0],l=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi;let u;for(;(u=l.exec(c))!==null;)a.push({start:u.index,length:u[0].length,error:`Value "${u[0]}" can't be safely passed as a path parameter`});if(a.sort((m,h)=>m.start-h.start),a.length>0){let m=0;const h=a.reduce((g,d)=>{const b=" ".repeat(d.start-m),w="^".repeat(d.length);return m=d.start+d.length,g+b+w},"");throw new I(`Path parameters result in path with invalid segments:
6
- ${a.map(g=>g.error).join(`
7
- `)}
8
- ${i}
9
- ${h}`)}return i},f=Zr(us);let hs=class extends k{list(e,t={},n){return this._client.getAPIList(f`/chat/completions/${e}/messages`,L,{query:t,...n})}};function ea(s){return typeof s.parse=="function"}const ct=s=>(s==null?void 0:s.role)==="assistant",ds=s=>(s==null?void 0:s.role)==="tool";var Nt,Ze,et,Oe,Ee,tt,Pe,ae,Te,lt,ut,be,fs;class Ht{constructor(){Nt.add(this),this.controller=new AbortController,Ze.set(this,void 0),et.set(this,()=>{}),Oe.set(this,()=>{}),Ee.set(this,void 0),tt.set(this,()=>{}),Pe.set(this,()=>{}),ae.set(this,{}),Te.set(this,!1),lt.set(this,!1),ut.set(this,!1),be.set(this,!1),C(this,Ze,new Promise((e,t)=>{C(this,et,e,"f"),C(this,Oe,t,"f")})),C(this,Ee,new Promise((e,t)=>{C(this,tt,e,"f"),C(this,Pe,t,"f")})),o(this,Ze,"f").catch(()=>{}),o(this,Ee,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},o(this,Nt,"m",fs).bind(this))},0)}_connected(){this.ended||(o(this,et,"f").call(this),this._emit("connect"))}get ended(){return o(this,Te,"f")}get errored(){return o(this,lt,"f")}get aborted(){return o(this,ut,"f")}abort(){this.controller.abort()}on(e,t){return(o(this,ae,"f")[e]||(o(this,ae,"f")[e]=[])).push({listener:t}),this}off(e,t){const n=o(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(o(this,ae,"f")[e]||(o(this,ae,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{C(this,be,!0),e!=="error"&&this.once("error",n),this.once(e,t)})}async done(){C(this,be,!0),await o(this,Ee,"f")}_emit(e,...t){if(o(this,Te,"f"))return;e==="end"&&(C(this,Te,!0),o(this,tt,"f").call(this));const n=o(this,ae,"f")[e];if(n&&(o(this,ae,"f")[e]=n.filter(r=>!r.once),n.forEach(({listener:r})=>r(...t))),e==="abort"){const r=t[0];!o(this,be,"f")&&!(n!=null&&n.length)&&Promise.reject(r),o(this,Oe,"f").call(this,r),o(this,Pe,"f").call(this,r),this._emit("end");return}if(e==="error"){const r=t[0];!o(this,be,"f")&&!(n!=null&&n.length)&&Promise.reject(r),o(this,Oe,"f").call(this,r),o(this,Pe,"f").call(this,r),this._emit("end")}}_emitFinal(){}}Ze=new WeakMap,et=new WeakMap,Oe=new WeakMap,Ee=new WeakMap,tt=new WeakMap,Pe=new WeakMap,ae=new WeakMap,Te=new WeakMap,lt=new WeakMap,ut=new WeakMap,be=new WeakMap,Nt=new WeakSet,fs=function(e){if(C(this,lt,!0),e instanceof Error&&e.name==="AbortError"&&(e=new z),e instanceof z)return C(this,ut,!0),this._emit("abort",e);if(e instanceof I)return this._emit("error",e);if(e instanceof Error){const t=new I(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new I(String(e)))};function Xt(s){return(s==null?void 0:s.$brand)==="auto-parseable-response-format"}function We(s){return(s==null?void 0:s.$brand)==="auto-parseable-tool"}function ta(s,e){return!e||!ms(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}}))}:Kt(s,e)}function Kt(s,e){const t=s.choices.map(n=>{var r;if(n.finish_reason==="length")throw new Vn;if(n.finish_reason==="content_filter")throw new Gn;return{...n,message:{...n.message,...n.message.tool_calls?{tool_calls:((r=n.message.tool_calls)==null?void 0:r.map(a=>sa(e,a)))??void 0}:void 0,parsed:n.message.content&&!n.message.refusal?na(e,n.message.content):null}}});return{...s,choices:t}}function na(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 sa(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:We(t)?t.$parseRaw(e.function.arguments):t!=null&&t.function.strict?JSON.parse(e.function.arguments):null}}}function ra(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 We(t)||(t==null?void 0:t.function.strict)||!1}function ms(s){var e;return Xt(s.response_format)?!0:((e=s.tools)==null?void 0:e.some(t=>We(t)||t.type==="function"&&t.function.strict===!0))??!1}function aa(s){for(const e of s??[]){if(e.type!=="function")throw new I(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new I(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var X,jt,ht,Ft,Lt,Dt,ps,gs;const ia=10;class _s extends Ht{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),ds(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(ct(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 I("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),o(this,X,"m",jt).call(this)}async finalMessage(){return await this.done(),o(this,X,"m",ht).call(this)}async finalFunctionToolCall(){return await this.done(),o(this,X,"m",Ft).call(this)}async finalFunctionToolCallResult(){return await this.done(),o(this,X,"m",Lt).call(this)}async totalUsage(){return await this.done(),o(this,X,"m",Dt).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){const e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);const t=o(this,X,"m",ht).call(this);t&&this._emit("finalMessage",t);const n=o(this,X,"m",jt).call(this);n&&this._emit("finalContent",n);const r=o(this,X,"m",Ft).call(this);r&&this._emit("finalFunctionToolCall",r);const a=o(this,X,"m",Lt).call(this);a!=null&&this._emit("finalFunctionToolCallResult",a),this._chatCompletions.some(i=>i.usage)&&this._emit("totalUsage",o(this,X,"m",Dt).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())),o(this,X,"m",ps).call(this,t);const a=await e.chat.completions.create({...t,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(Kt(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,...c}=t,l=typeof a!="string"&&((d=a==null?void 0:a.function)==null?void 0:d.name),{maxChatCompletions:u=ia}=n||{},m=t.tools.map(A=>{if(We(A)){if(!A.$callback)throw new I("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}),h={};for(const A of m)A.type==="function"&&(h[A.function.name||A.function.function.name]=A.function);const g="tools"in t?m.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<u;++A){const p=(b=(await this._createChatCompletion(e,{...c,tool_choice:a,tools:g,messages:[...this.messages]},n)).choices[0])==null?void 0:b.message;if(!p)throw new I("missing message in ChatCompletion response");if(!((w=p.tool_calls)!=null&&w.length))return;for(const y of p.tool_calls){if(y.type!=="function")continue;const _=y.id,{name:v,arguments:$}=y.function,R=h[v];if(R){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:_,content:M});continue}}else{const M=`Invalid tool_call: ${JSON.stringify(v)}. Available options are: ${Object.keys(h).map(se=>JSON.stringify(se)).join(", ")}. Please try again`;this._addMessage({role:r,tool_call_id:_,content:M});continue}let F;try{F=ea(R)?await R.parse($):$}catch(M){const se=M instanceof Error?M.message:String(M);this._addMessage({role:r,tool_call_id:_,content:se});continue}const x=await R.function(F,this),T=o(this,X,"m",gs).call(this,x);if(this._addMessage({role:r,tool_call_id:_,content:T}),l)return}}}}X=new WeakSet,jt=function(){return o(this,X,"m",ht).call(this).content??null},ht=function(){let e=this.messages.length;for(;e-- >0;){const t=this.messages[e];if(ct(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new I("stream ended without producing a ChatCompletionMessage with role=assistant")},Ft=function(){var e,t;for(let n=this.messages.length-1;n>=0;n--){const r=this.messages[n];if(ct(r)&&((e=r==null?void 0:r.tool_calls)!=null&&e.length))return(t=r.tool_calls.at(-1))==null?void 0:t.function}},Lt=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(ds(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}},Dt=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},ps=function(e){if(e.n!=null&&e.n>1)throw new I("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},gs=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};class Vt extends _s{static runTools(e,t,n){const r=new Vt,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),ct(e)&&e.content&&this._emit("content",e.content)}}const ys=1,ws=2,bs=4,Ss=8,xs=16,As=32,vs=64,Cs=128,Is=256,Rs=Cs|Is,ks=xs|As|Rs|vs,$s=ys|ws|ks,Os=bs|Ss,oa=$s|Os,W={STR:ys,NUM:ws,ARR:bs,OBJ:Ss,NULL:xs,BOOL:As,NAN:vs,INFINITY:Cs,MINUS_INFINITY:Is,INF:Rs,SPECIAL:ks,ATOM:$s,COLLECTION:Os,ALL:oa};class ca extends Error{}class la extends Error{}function ua(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 ha(s.trim(),e)}const ha=(s,e)=>{const t=s.length;let n=0;const r=g=>{throw new ca(`${g} at position ${n}`)},a=g=>{throw new la(`${g} at position ${n}`)},i=()=>(h(),n>=t&&r("Unexpected end of input"),s[n]==='"'?c():s[n]==="{"?l():s[n]==="["?u():s.substring(n,n+4)==="null"||W.NULL&e&&t-n<4&&"null".startsWith(s.substring(n))?(n+=4,null):s.substring(n,n+4)==="true"||W.BOOL&e&&t-n<4&&"true".startsWith(s.substring(n))?(n+=4,!0):s.substring(n,n+5)==="false"||W.BOOL&e&&t-n<5&&"false".startsWith(s.substring(n))?(n+=5,!1):s.substring(n,n+8)==="Infinity"||W.INFINITY&e&&t-n<8&&"Infinity".startsWith(s.substring(n))?(n+=8,1/0):s.substring(n,n+9)==="-Infinity"||W.MINUS_INFINITY&e&&1<t-n&&t-n<9&&"-Infinity".startsWith(s.substring(n))?(n+=9,-1/0):s.substring(n,n+3)==="NaN"||W.NAN&e&&t-n<3&&"NaN".startsWith(s.substring(n))?(n+=3,NaN):m()),c=()=>{const g=n;let d=!1;for(n++;n<t&&(s[n]!=='"'||d&&s[n-1]==="\\");)d=s[n]==="\\"?!d:!1,n++;if(s.charAt(n)=='"')try{return JSON.parse(s.substring(g,++n-Number(d)))}catch(b){a(String(b))}else if(W.STR&e)try{return JSON.parse(s.substring(g,n-Number(d))+'"')}catch{return JSON.parse(s.substring(g,s.lastIndexOf("\\"))+'"')}r("Unterminated string literal")},l=()=>{n++,h();const g={};try{for(;s[n]!=="}";){if(h(),n>=t&&W.OBJ&e)return g;const d=c();h(),n++;try{const b=i();Object.defineProperty(g,d,{value:b,writable:!0,enumerable:!0,configurable:!0})}catch(b){if(W.OBJ&e)return g;throw b}h(),s[n]===","&&n++}}catch{if(W.OBJ&e)return g;r("Expected '}' at end of object")}return n++,g},u=()=>{n++;const g=[];try{for(;s[n]!=="]";)g.push(i()),h(),s[n]===","&&n++}catch{if(W.ARR&e)return g;r("Expected ']' at end of array")}return n++,g},m=()=>{if(n===0){s==="-"&&W.NUM&e&&r("Not sure what '-' is");try{return JSON.parse(s)}catch(d){if(W.NUM&e)try{return s[s.length-1]==="."?JSON.parse(s.substring(0,s.lastIndexOf("."))):JSON.parse(s.substring(0,s.lastIndexOf("e")))}catch{}a(String(d))}}const g=n;for(s[n]==="-"&&n++;s[n]&&!",]}".includes(s[n]);)n++;n==t&&!(W.NUM&e)&&r("Unterminated number literal");try{return JSON.parse(s.substring(g,n))}catch{s.substring(g,n)==="-"&&W.NUM&e&&r("Not sure what '-' is");try{return JSON.parse(s.substring(g,s.lastIndexOf("e")))}catch(b){a(String(b))}}},h=()=>{for(;n<t&&`
10
- \r `.includes(s[n]);)n++};return i()},In=s=>ua(s,W.ALL^W.NUM);var D,re,pe,oe,vt,Xe,Ct,It,Rt,Ke,kt,Rn;class De extends _s{constructor(e){super(),D.add(this),re.set(this,void 0),pe.set(this,void 0),oe.set(this,void 0),C(this,re,e),C(this,pe,[])}get currentChatCompletionSnapshot(){return o(this,oe,"f")}static fromReadableStream(e){const t=new De(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,n){const r=new De(t);return r._run(()=>r._runChatCompletion(e,{...t,stream:!0},{...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"stream"}})),r}async _createChatCompletion(e,t,n){var i;super._createChatCompletion;const r=n==null?void 0:n.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),o(this,D,"m",vt).call(this);const a=await e.chat.completions.create({...t,stream:!0},{...n,signal:this.controller.signal});this._connected();for await(const c of a)o(this,D,"m",Ct).call(this,c);if((i=a.controller.signal)!=null&&i.aborted)throw new z;return this._addChatCompletion(o(this,D,"m",Ke).call(this))}async _fromReadableStream(e,t){var i;const n=t==null?void 0:t.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),o(this,D,"m",vt).call(this),this._connected();const r=ne.fromReadableStream(e,this.controller);let a;for await(const c of r)a&&a!==c.id&&this._addChatCompletion(o(this,D,"m",Ke).call(this)),o(this,D,"m",Ct).call(this,c),a=c.id;if((i=r.controller.signal)!=null&&i.aborted)throw new z;return this._addChatCompletion(o(this,D,"m",Ke).call(this))}[(re=new WeakMap,pe=new WeakMap,oe=new WeakMap,D=new WeakSet,vt=function(){this.ended||C(this,oe,void 0)},Xe=function(t){let n=o(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},o(this,pe,"f")[t.index]=n,n)},Ct=function(t){var r,a,i,c,l,u,m,h,g,d,b,w,A,O,p;if(this.ended)return;const n=o(this,D,"m",Rn).call(this,t);this._emit("chunk",t,n);for(const y of t.choices){const _=n.choices[y.index];y.delta.content!=null&&((r=_.message)==null?void 0:r.role)==="assistant"&&((a=_.message)!=null&&a.content)&&(this._emit("content",y.delta.content,_.message.content),this._emit("content.delta",{delta:y.delta.content,snapshot:_.message.content,parsed:_.message.parsed})),y.delta.refusal!=null&&((i=_.message)==null?void 0:i.role)==="assistant"&&((c=_.message)!=null&&c.refusal)&&this._emit("refusal.delta",{delta:y.delta.refusal,snapshot:_.message.refusal}),((l=y.logprobs)==null?void 0:l.content)!=null&&((u=_.message)==null?void 0:u.role)==="assistant"&&this._emit("logprobs.content.delta",{content:(m=y.logprobs)==null?void 0:m.content,snapshot:((h=_.logprobs)==null?void 0:h.content)??[]}),((g=y.logprobs)==null?void 0:g.refusal)!=null&&((d=_.message)==null?void 0:d.role)==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:(b=y.logprobs)==null?void 0:b.refusal,snapshot:((w=_.logprobs)==null?void 0:w.refusal)??[]});const v=o(this,D,"m",Xe).call(this,_);_.finish_reason&&(o(this,D,"m",Rt).call(this,_),v.current_tool_call_index!=null&&o(this,D,"m",It).call(this,_,v.current_tool_call_index));for(const $ of y.delta.tool_calls??[])v.current_tool_call_index!==$.index&&(o(this,D,"m",Rt).call(this,_),v.current_tool_call_index!=null&&o(this,D,"m",It).call(this,_,v.current_tool_call_index)),v.current_tool_call_index=$.index;for(const $ of y.delta.tool_calls??[]){const R=(A=_.message.tool_calls)==null?void 0:A[$.index];R!=null&&R.type&&((R==null?void 0:R.type)==="function"?this._emit("tool_calls.function.arguments.delta",{name:(O=R.function)==null?void 0:O.name,index:$.index,arguments:R.function.arguments,parsed_arguments:R.function.parsed_arguments,arguments_delta:((p=$.function)==null?void 0:p.arguments)??""}):(R==null||R.type,void 0))}}},It=function(t,n){var i,c,l;if(o(this,D,"m",Xe).call(this,t).done_tool_calls.has(n))return;const a=(i=t.message.tool_calls)==null?void 0:i[n];if(!a)throw new Error("no tool call snapshot");if(!a.type)throw new Error("tool call snapshot missing `type`");if(a.type==="function"){const u=(l=(c=o(this,re,"f"))==null?void 0:c.tools)==null?void 0:l.find(m=>m.type==="function"&&m.function.name===a.function.name);this._emit("tool_calls.function.arguments.done",{name:a.function.name,index:n,arguments:a.function.arguments,parsed_arguments:We(u)?u.$parseRaw(a.function.arguments):u!=null&&u.function.strict?JSON.parse(a.function.arguments):null})}else a.type},Rt=function(t){var r,a;const n=o(this,D,"m",Xe).call(this,t);if(t.message.content&&!n.content_done){n.content_done=!0;const i=o(this,D,"m",kt).call(this);this._emit("content.done",{content:t.message.content,parsed:i?i.$parseRaw(t.message.content):null})}t.message.refusal&&!n.refusal_done&&(n.refusal_done=!0,this._emit("refusal.done",{refusal:t.message.refusal})),(r=t.logprobs)!=null&&r.content&&!n.logprobs_content_done&&(n.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:t.logprobs.content})),(a=t.logprobs)!=null&&a.refusal&&!n.logprobs_refusal_done&&(n.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:t.logprobs.refusal}))},Ke=function(){if(this.ended)throw new I("stream has ended, this shouldn't happen");const t=o(this,oe,"f");if(!t)throw new I("request ended without sending any chunks");return C(this,oe,void 0),C(this,pe,[]),da(t,o(this,re,"f"))},kt=function(){var n;const t=(n=o(this,re,"f"))==null?void 0:n.response_format;return Xt(t)?t:null},Rn=function(t){var n,r,a,i;let c=o(this,oe,"f");const{choices:l,...u}=t;c?Object.assign(c,u):c=C(this,oe,{...u,choices:[]});for(const{delta:m,finish_reason:h,index:g,logprobs:d=null,...b}of t.choices){let w=c.choices[g];if(w||(w=c.choices[g]={finish_reason:h,index:g,message:{},logprobs:d,...b}),d)if(!w.logprobs)w.logprobs=Object.assign({},d);else{const{content:$,refusal:R,...F}=d;Object.assign(w.logprobs,F),$&&((n=w.logprobs).content??(n.content=[]),w.logprobs.content.push(...$)),R&&((r=w.logprobs).refusal??(r.refusal=[]),w.logprobs.refusal.push(...R))}if(h&&(w.finish_reason=h,o(this,re,"f")&&ms(o(this,re,"f")))){if(h==="length")throw new Vn;if(h==="content_filter")throw new Gn}if(Object.assign(w,b),!m)continue;const{content:A,refusal:O,function_call:p,role:y,tool_calls:_,...v}=m;if(Object.assign(w.message,v),O&&(w.message.refusal=(w.message.refusal||"")+O),y&&(w.message.role=y),p&&(w.message.function_call?(p.name&&(w.message.function_call.name=p.name),p.arguments&&((a=w.message.function_call).arguments??(a.arguments=""),w.message.function_call.arguments+=p.arguments)):w.message.function_call=p),A&&(w.message.content=(w.message.content||"")+A,!w.message.refusal&&o(this,D,"m",kt).call(this)&&(w.message.parsed=In(w.message.content))),_){w.message.tool_calls||(w.message.tool_calls=[]);for(const{index:$,id:R,type:F,function:x,...T}of _){const M=(i=w.message.tool_calls)[$]??(i[$]={});Object.assign(M,T),R&&(M.id=R),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,ra(o(this,re,"f"),M)&&(M.function.parsed_arguments=In(M.function.arguments)))}}}return c},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 da(s,e){const{id:t,choices:n,created:r,model:a,system_fingerprint:i,...c}=s,l={...c,id:t,choices:n.map(({message:u,finish_reason:m,index:h,logprobs:g,...d})=>{if(!m)throw new I(`missing finish_reason for choice ${h}`);const{content:b=null,function_call:w,tool_calls:A,...O}=u,p=u.role;if(!p)throw new I(`missing role for choice ${h}`);if(w){const{arguments:y,name:_}=w;if(y==null)throw new I(`missing function_call.arguments for choice ${h}`);if(!_)throw new I(`missing function_call.name for choice ${h}`);return{...d,message:{content:b,function_call:{arguments:y,name:_},role:p,refusal:u.refusal??null},finish_reason:m,index:h,logprobs:g}}return A?{...d,index:h,finish_reason:m,logprobs:g,message:{...O,role:p,content:b,refusal:u.refusal??null,tool_calls:A.map((y,_)=>{const{function:v,type:$,id:R,...F}=y,{arguments:x,name:T,...M}=v||{};if(R==null)throw new I(`missing choices[${h}].tool_calls[${_}].id
11
- ${Ve(s)}`);if($==null)throw new I(`missing choices[${h}].tool_calls[${_}].type
12
- ${Ve(s)}`);if(T==null)throw new I(`missing choices[${h}].tool_calls[${_}].function.name
13
- ${Ve(s)}`);if(x==null)throw new I(`missing choices[${h}].tool_calls[${_}].function.arguments
14
- ${Ve(s)}`);return{...F,id:R,type:$,function:{...M,name:T,arguments:x}}})}}:{...d,message:{...O,content:b,role:p,refusal:u.refusal??null},finish_reason:m,index:h,logprobs:g}}),created:r,model:a,object:"chat.completion",...i?{system_fingerprint:i}:{}};return ta(l,e)}function Ve(s){return JSON.stringify(s)}class dt extends De{static fromReadableStream(e){const t=new dt(null);return t._run(()=>t._fromReadableStream(e)),t}static runTools(e,t,n){const r=new dt(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 Gt=class extends k{constructor(){super(...arguments),this.messages=new hs(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 aa(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=>Kt(n,e))}runTools(e,t){return e.stream?dt.runTools(this._client,e,t):Vt.runTools(this._client,e,t)}stream(e,t){return De.createChatCompletion(this._client,e,t)}};Gt.Messages=hs;class Qt extends k{constructor(){super(...arguments),this.completions=new Gt(this._client)}}Qt.Completions=Gt;const Es=Symbol("brand.privateNullableHeaders");function*fa(s){if(!s)return;if(Es 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():dn(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=dn(n[1])?n[1]:[n[1]];let i=!1;for(const c of a)c!==void 0&&(e&&!i&&(i=!0,yield[r,null]),yield[r,c])}}const S=s=>{const e=new Headers,t=new Set;for(const n of s){const r=new Set;for(const[a,i]of fa(n)){const c=a.toLowerCase();r.has(c)||(e.delete(a),r.add(c)),i===null?(e.delete(a),t.add(c)):(e.append(a,i),t.delete(c))}}return{[Es]:!0,values:e,nulls:t}};class Ps 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 Ts 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 Ms extends k{create(e,t){return this._client.post("/audio/translations",fe({body:e,...t,__metadata:{model:e.model}},this._client))}}class Ue extends k{constructor(){super(...arguments),this.transcriptions=new Ts(this._client),this.translations=new Ms(this._client),this.speech=new Ps(this._client)}}Ue.Transcriptions=Ts;Ue.Translations=Ms;Ue.Speech=Ps;class Ns 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 js 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 Fs 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 Ls 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 yt extends k{constructor(){super(...arguments),this.sessions=new Fs(this._client),this.transcriptionSessions=new Ls(this._client)}}yt.Sessions=Fs;yt.TranscriptionSessions=Ls;class Ds 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 Bs 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 ma=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 $t={};const ge=s=>{var e,t,n,r;if(typeof globalThis.process<"u")return((e=$t==null?void 0:$t[s])==null?void 0:e.trim())??void 0;if(typeof globalThis.Deno<"u")return(r=(n=(t=globalThis.Deno.env)==null?void 0:t.get)==null?void 0:n.call(t,s))==null?void 0:r.trim()};var J,he,Bt,te,nt,Y,de,xe,ue,ft,Q,st,rt,Fe,Me,Ne,kn,$n,On,En,Pn,Tn,Mn;class Le extends Ht{constructor(){super(...arguments),J.add(this),Bt.set(this,[]),te.set(this,{}),nt.set(this,{}),Y.set(this,void 0),de.set(this,void 0),xe.set(this,void 0),ue.set(this,void 0),ft.set(this,void 0),Q.set(this,void 0),st.set(this,void 0),rt.set(this,void 0),Fe.set(this,void 0)}[(Bt=new WeakMap,te=new WeakMap,nt=new WeakMap,Y=new WeakMap,de=new WeakMap,xe=new WeakMap,ue=new WeakMap,ft=new WeakMap,Q=new WeakMap,st=new WeakMap,rt=new WeakMap,Fe=new WeakMap,J=new WeakSet,Symbol.asyncIterator)](){const e=[],t=[];let n=!1;return this.on("event",r=>{const a=t.shift();a?a.resolve(r):e.push(r)}),this.on("end",()=>{n=!0;for(const r of t)r.resolve(void 0);t.length=0}),this.on("abort",r=>{n=!0;for(const a of t)a.reject(r);t.length=0}),this.on("error",r=>{n=!0;for(const a of t)a.reject(r);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((a,i)=>t.push({resolve:a,reject:i})).then(a=>a?{value:a,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){const t=new he;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){var a;const n=t==null?void 0:t.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),this._connected();const r=ne.fromReadableStream(e,this.controller);for await(const i of r)o(this,J,"m",Me).call(this,i);if((a=r.controller.signal)!=null&&a.aborted)throw new z;return this._addRun(o(this,J,"m",Ne).call(this))}toReadableStream(){return new ne(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,n,r){const a=new he;return a._run(()=>a._runToolAssistantStream(e,t,n,{...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"stream"}})),a}async _createToolAssistantStream(e,t,n,r){var l;const a=r==null?void 0:r.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener("abort",()=>this.controller.abort()));const i={...n,stream:!0},c=await e.submitToolOutputs(t,i,{...r,signal:this.controller.signal});this._connected();for await(const u of c)o(this,J,"m",Me).call(this,u);if((l=c.controller.signal)!=null&&l.aborted)throw new z;return this._addRun(o(this,J,"m",Ne).call(this))}static createThreadAssistantStream(e,t,n){const r=new he;return r._run(()=>r._threadAssistantStream(e,t,{...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"stream"}})),r}static createAssistantStream(e,t,n,r){const a=new he;return a._run(()=>a._runAssistantStream(e,t,n,{...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"stream"}})),a}currentEvent(){return o(this,st,"f")}currentRun(){return o(this,rt,"f")}currentMessageSnapshot(){return o(this,Y,"f")}currentRunStepSnapshot(){return o(this,Fe,"f")}async finalRunSteps(){return await this.done(),Object.values(o(this,te,"f"))}async finalMessages(){return await this.done(),Object.values(o(this,nt,"f"))}async finalRun(){if(await this.done(),!o(this,de,"f"))throw Error("Final run was not received.");return o(this,de,"f")}async _createThreadAssistantStream(e,t,n){var c;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)o(this,J,"m",Me).call(this,l);if((c=i.controller.signal)!=null&&c.aborted)throw new z;return this._addRun(o(this,J,"m",Ne).call(this))}async _createAssistantStream(e,t,n,r){var l;const a=r==null?void 0:r.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener("abort",()=>this.controller.abort()));const i={...n,stream:!0},c=await e.create(t,i,{...r,signal:this.controller.signal});this._connected();for await(const u of c)o(this,J,"m",Me).call(this,u);if((l=c.controller.signal)!=null&&l.aborted)throw new z;return this._addRun(o(this,J,"m",Ne).call(this))}static accumulateDelta(e,t){for(const[n,r]of Object.entries(t)){if(!e.hasOwnProperty(n)){e[n]=r;continue}let a=e[n];if(a==null){e[n]=r;continue}if(n==="index"||n==="type"){e[n]=r;continue}if(typeof a=="string"&&typeof r=="string")a+=r;else if(typeof a=="number"&&typeof r=="number")a+=r;else if(St(a)&&St(r))a=this.accumulateDelta(a,r);else if(Array.isArray(a)&&Array.isArray(r)){if(a.every(i=>typeof i=="string"||typeof i=="number")){a.push(...r);continue}for(const i of r){if(!St(i))throw new Error(`Expected array delta entry to be an object but got: ${i}`);const c=i.index;if(c==null)throw console.error(i),new Error("Expected array delta entry to have an `index` property");if(typeof c!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${c}`);const l=a[c];l==null?a.push(i):a[c]=this.accumulateDelta(l,i)}continue}else throw Error(`Unhandled record type: ${n}, deltaValue: ${r}, accValue: ${a}`);e[n]=a}return e}_addRun(e){return e}async _threadAssistantStream(e,t,n){return await this._createThreadAssistantStream(t,e,n)}async _runAssistantStream(e,t,n,r){return await this._createAssistantStream(t,e,n,r)}async _runToolAssistantStream(e,t,n,r){return await this._createToolAssistantStream(t,e,n,r)}}he=Le,Me=function(e){if(!this.ended)switch(C(this,st,e),o(this,J,"m",On).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":o(this,J,"m",Mn).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":o(this,J,"m",$n).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":o(this,J,"m",kn).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},Ne=function(){if(this.ended)throw new I("stream has ended, this shouldn't happen");if(!o(this,de,"f"))throw Error("Final run has not been received");return o(this,de,"f")},kn=function(e){const[t,n]=o(this,J,"m",Pn).call(this,e,o(this,Y,"f"));C(this,Y,t),o(this,nt,"f")[t.id]=t;for(const r of n){const a=t.content[r.index];(a==null?void 0:a.type)=="text"&&this._emit("textCreated",a.text)}switch(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,t),e.data.delta.content)for(const r of e.data.delta.content){if(r.type=="text"&&r.text){let a=r.text,i=t.content[r.index];if(i&&i.type=="text")this._emit("textDelta",a,i.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(r.index!=o(this,xe,"f")){if(o(this,ue,"f"))switch(o(this,ue,"f").type){case"text":this._emit("textDone",o(this,ue,"f").text,o(this,Y,"f"));break;case"image_file":this._emit("imageFileDone",o(this,ue,"f").image_file,o(this,Y,"f"));break}C(this,xe,r.index)}C(this,ue,t.content[r.index])}break;case"thread.message.completed":case"thread.message.incomplete":if(o(this,xe,"f")!==void 0){const r=e.data.content[o(this,xe,"f")];if(r)switch(r.type){case"image_file":this._emit("imageFileDone",r.image_file,o(this,Y,"f"));break;case"text":this._emit("textDone",r.text,o(this,Y,"f"));break}}o(this,Y,"f")&&this._emit("messageDone",e.data),C(this,Y,void 0)}},$n=function(e){const t=o(this,J,"m",En).call(this,e);switch(C(this,Fe,t),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":const n=e.data.delta;if(n.step_details&&n.step_details.type=="tool_calls"&&n.step_details.tool_calls&&t.step_details.type=="tool_calls")for(const a of n.step_details.tool_calls)a.index==o(this,ft,"f")?this._emit("toolCallDelta",a,t.step_details.tool_calls[a.index]):(o(this,Q,"f")&&this._emit("toolCallDone",o(this,Q,"f")),C(this,ft,a.index),C(this,Q,t.step_details.tool_calls[a.index]),o(this,Q,"f")&&this._emit("toolCallCreated",o(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":C(this,Fe,void 0),e.data.step_details.type=="tool_calls"&&o(this,Q,"f")&&(this._emit("toolCallDone",o(this,Q,"f")),C(this,Q,void 0)),this._emit("runStepDone",e.data,t);break}},On=function(e){o(this,Bt,"f").push(e),this._emit("event",e)},En=function(e){switch(e.event){case"thread.run.step.created":return o(this,te,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=o(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);o(this,te,"f")[e.data.id]=r}return o(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":o(this,te,"f")[e.data.id]=e.data;break}if(o(this,te,"f")[e.data.id])return o(this,te,"f")[e.data.id];throw new Error("No snapshot available")},Pn=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]=o(this,J,"m",Tn).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")},Tn=function(e,t){return he.accumulateDelta(t,e)},Mn=function(e){switch(C(this,rt,e.data),e.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":case"thread.run.incomplete":C(this,de,e.data),o(this,Q,"f")&&(this._emit("toolCallDone",o(this,Q,"f")),C(this,Q,void 0));break}};let zt=class extends k{constructor(){super(...arguments),this.steps=new Bs(this._client)}create(e,t,n){const{include:r,...a}=t;return this._client.post(f`/threads/${e}/runs`,{query:{include:r},body:a,...n,headers:S([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers]),stream:t.stream??!1})}retrieve(e,t,n){const{thread_id:r}=t;return this._client.get(f`/threads/${r}/runs/${e}`,{...n,headers:S([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}update(e,t,n){const{thread_id:r,...a}=t;return this._client.post(f`/threads/${r}/runs/${e}`,{body:a,...n,headers:S([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}list(e,t={},n){return this._client.getAPIList(f`/threads/${e}/runs`,L,{query:t,...n,headers:S([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}cancel(e,t,n){const{thread_id:r}=t;return this._client.post(f`/threads/${r}/runs/${e}/cancel`,{...n,headers:S([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}async createAndPoll(e,t,n){const r=await this.create(e,t,n);return await this.poll(r.id,{thread_id:e},n)}createAndStream(e,t,n){return Le.createAssistantStream(e,this._client.beta.threads.runs,t,n)}async poll(e,t,n){var a;const r=S([n==null?void 0:n.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":((a=n==null?void 0:n.pollIntervalMs)==null?void 0:a.toString())??void 0}]);for(;;){const{data:i,response:c}=await this.retrieve(e,t,{...n,headers:{...n==null?void 0:n.headers,...r}}).withResponse();switch(i.status){case"queued":case"in_progress":case"cancelling":let l=5e3;if(n!=null&&n.pollIntervalMs)l=n.pollIntervalMs;else{const u=c.headers.get("openai-poll-after-ms");if(u){const m=parseInt(u);isNaN(m)||(l=m)}}await Be(l);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return i}}}stream(e,t,n){return Le.createAssistantStream(e,this._client.beta.threads.runs,t,n)}submitToolOutputs(e,t,n){const{thread_id:r,...a}=t;return this._client.post(f`/threads/${r}/runs/${e}/submit_tool_outputs`,{body:a,...n,headers:S([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers]),stream:t.stream??!1})}async submitToolOutputsAndPoll(e,t,n){const r=await this.submitToolOutputs(e,t,n);return await this.poll(r.id,t,n)}submitToolOutputsStream(e,t,n){return Le.createToolAssistantStream(e,this._client.beta.threads.runs,t,n)}};zt.Steps=Bs;class wt extends k{constructor(){super(...arguments),this.runs=new zt(this._client),this.messages=new Ds(this._client)}create(e={},t){return this._client.post("/threads",{body:e,...t,headers:S([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers])})}retrieve(e,t){return this._client.get(f`/threads/${e}`,{...t,headers:S([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers])})}update(e,t,n){return this._client.post(f`/threads/${e}`,{body:t,...n,headers:S([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}delete(e,t){return this._client.delete(f`/threads/${e}`,{...t,headers:S([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers])})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:S([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers]),stream:e.stream??!1})}async createAndRunPoll(e,t){const n=await this.createAndRun(e,t);return await this.runs.poll(n.id,{thread_id:n.thread_id},t)}createAndRunStream(e,t){return Le.createThreadAssistantStream(e,this._client.beta.threads,t)}}wt.Runs=zt;wt.Messages=Ds;class qe extends k{constructor(){super(...arguments),this.realtime=new yt(this._client),this.assistants=new js(this._client),this.threads=new wt(this._client)}}qe.Realtime=yt;qe.Assistants=js;qe.Threads=wt;class Ws extends k{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}}class Us 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 Yt=class extends k{constructor(){super(...arguments),this.content=new Us(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])})}};Yt.Content=Us;class Zt extends k{constructor(){super(...arguments),this.files=new Yt(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])})}}Zt.Files=Yt;class qs extends k{create(e,t){const n=!!e.encoding_format;let r=n?e.encoding_format:"base64";n&&q(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);const a=this._client.post("/embeddings",{body:{...e,encoding_format:r},...t});return n?a:(q(this._client).debug("embeddings/decoding base64 embeddings from base64"),a._thenUnwrap(i=>(i&&i.data&&i.data.forEach(c=>{const l=c.embedding;c.embedding=ma(l)}),i)))}}class Js 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 en extends k{constructor(){super(...arguments),this.outputItems=new Js(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)}}en.OutputItems=Js;class tn extends k{constructor(){super(...arguments),this.runs=new en(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)}}tn.Runs=en;let Hs=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=1800*1e3}={}){const r=new Set(["processed","error","deleted"]),a=Date.now();let i=await this.retrieve(e);for(;!i.status||!r.has(i.status);)if(await Be(t),i=await this.retrieve(e),Date.now()-a>n)throw new qt({message:`Giving up on waiting for file ${e} to finish processing after ${n} milliseconds.`});return i}};class Xs extends k{}let Ks=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 nn extends k{constructor(){super(...arguments),this.graders=new Ks(this._client)}}nn.Graders=Ks;class Vs extends k{create(e,t,n){return this._client.getAPIList(f`/fine_tuning/checkpoints/${e}/permissions`,_t,{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 sn=class extends k{constructor(){super(...arguments),this.permissions=new Vs(this._client)}};sn.Permissions=Vs;class Gs extends k{list(e,t={},n){return this._client.getAPIList(f`/fine_tuning/jobs/${e}/checkpoints`,L,{query:t,...n})}}class rn extends k{constructor(){super(...arguments),this.checkpoints=new Gs(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)}}rn.Checkpoints=Gs;class Ae extends k{constructor(){super(...arguments),this.methods=new Xs(this._client),this.jobs=new rn(this._client),this.checkpoints=new sn(this._client),this.alpha=new nn(this._client)}}Ae.Methods=Xs;Ae.Jobs=rn;Ae.Checkpoints=sn;Ae.Alpha=nn;class Qs extends k{}class an extends k{constructor(){super(...arguments),this.graderModels=new Qs(this._client)}}an.GraderModels=Qs;class zs 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,stream:e.stream??!1},this._client))}generate(e,t){return this._client.post("/images/generations",{body:e,...t,stream:e.stream??!1})}}class Ys extends k{retrieve(e,t){return this._client.get(f`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",_t,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 pa(s,e){return!e||!_a(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)}:er(s,e)}function er(s,e){const t=s.output.map(r=>{if(r.type==="function_call")return{...r,parsed_arguments:ba(e,r)};if(r.type==="message"){const a=r.content.map(i=>i.type==="output_text"?{...i,parsed:ga(e,i.text)}:i);return{...r,content:a}}return r}),n=Object.assign({},s,{output:t});return Object.getOwnPropertyDescriptor(s,"output_text")||Wt(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 ga(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 _a(s){var e;return!!Xt((e=s.text)==null?void 0:e.format)}function ya(s){return(s==null?void 0:s.$brand)==="auto-parseable-tool"}function wa(s,e){return s.find(t=>t.type==="function"&&t.name===e)}function ba(s,e){const t=wa(s.tools??[],e.name);return{...e,...e,parsed_arguments:ya(t)?t.$parseRaw(e.arguments):t!=null&&t.strict?JSON.parse(e.arguments):null}}function Wt(s){const e=[];for(const t of s.output)if(t.type==="message")for(const n of t.content)n.type==="output_text"&&e.push(n.text);s.output_text=e.join("")}var _e,Ge,ce,Qe,Nn,jn,Fn,Ln;class on extends Ht{constructor(e){super(),_e.add(this),Ge.set(this,void 0),ce.set(this,void 0),Qe.set(this,void 0),C(this,Ge,e)}static createResponse(e,t,n){const r=new on(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 c;const r=n==null?void 0:n.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),o(this,_e,"m",Nn).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)o(this,_e,"m",jn).call(this,l,i);if((c=a.controller.signal)!=null&&c.aborted)throw new z;return o(this,_e,"m",Fn).call(this)}[(Ge=new WeakMap,ce=new WeakMap,Qe=new WeakMap,_e=new WeakSet,Nn=function(){this.ended||C(this,ce,void 0)},jn=function(t,n){if(this.ended)return;const r=(i,c)=>{(n==null||c.sequence_number>n)&&this._emit(i,c)},a=o(this,_e,"m",Ln).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 I(`missing output at index ${t.output_index}`);if(i.type==="message"){const c=i.content[t.content_index];if(!c)throw new I(`missing content at index ${t.content_index}`);if(c.type!=="output_text")throw new I(`expected content to be 'output_text', got ${c.type}`);r("response.output_text.delta",{...t,snapshot:c.text})}break}case"response.function_call_arguments.delta":{const i=a.output[t.output_index];if(!i)throw new I(`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}},Fn=function(){if(this.ended)throw new I("stream has ended, this shouldn't happen");const t=o(this,ce,"f");if(!t)throw new I("request ended without sending any events");C(this,ce,void 0);const n=Sa(t,o(this,Ge,"f"));return C(this,Qe,n),n},Ln=function(t){let n=o(this,ce,"f");if(!n){if(t.type!=="response.created")throw new I(`When snapshot hasn't been set yet, expected 'response.created' event, got ${t.type}`);return n=C(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 I(`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 I(`missing output at index ${t.output_index}`);if(r.type==="message"){const a=r.content[t.content_index];if(!a)throw new I(`missing content at index ${t.content_index}`);if(a.type!=="output_text")throw new I(`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 I(`missing output at index ${t.output_index}`);r.type==="function_call"&&(r.arguments+=t.delta);break}case"response.completed":{C(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=o(this,Qe,"f");if(!e)throw new I("stream ended without producing a ChatCompletion");return e}}function Sa(s,e){return pa(s,e)}class tr extends k{list(e,t={},n){return this._client.getAPIList(f`/responses/${e}/input_items`,L,{query:t,...n})}}class cn extends k{constructor(){super(...arguments),this.inputItems=new tr(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"&&Wt(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"&&Wt(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=>er(n,e))}stream(e,t){return on.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(f`/responses/${e}/cancel`,t)}}cn.InputItems=tr;class nr extends k{create(e,t,n){return this._client.post(f`/uploads/${e}/parts`,fe({body:t,...n},this._client))}}class ln extends k{constructor(){super(...arguments),this.parts=new nr(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})}}ln.Parts=nr;const xa=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 sr 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:c}=await this.retrieve(t,{vector_store_id:e},{...n,headers:r}).withResponse();switch(i.status){case"in_progress":let l=5e3;if(n!=null&&n.pollIntervalMs)l=n.pollIntervalMs;else{const u=c.headers.get("openai-poll-after-ms");if(u){const m=parseInt(u);isNaN(m)||(l=m)}}await Be(l);break;case"failed":case"cancelled":case"completed":return i}}}async uploadAndPoll(e,{files:t,fileIds:n=[]},r){if(t==null||t.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");const a=(r==null?void 0:r.maxConcurrency)??5,i=Math.min(a,t.length),c=this._client,l=t.values(),u=[...n];async function m(g){for(let d of g){const b=await c.files.create({file:d,purpose:"assistants"},r);u.push(b.id)}}const h=Array(i).fill(l).map(m);return await xa(h),await this.createAndPoll(e,{file_ids:u})}}class rr 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(),c=i.data;switch(c.status){case"in_progress":let l=5e3;if(n!=null&&n.pollIntervalMs)l=n.pollIntervalMs;else{const u=i.response.headers.get("openai-poll-after-ms");if(u){const m=parseInt(u);isNaN(m)||(l=m)}}await Be(l);break;case"failed":case"completed":return c}}}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`,_t,{...n,headers:S([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}}class bt extends k{constructor(){super(...arguments),this.files=new rr(this._client),this.fileBatches=new sr(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`,_t,{body:t,method:"post",...n,headers:S([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}}bt.Files=rr;bt.FileBatches=sr;var Se,ar,at;class ir 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");o(this,Se,"m",ar).call(this,n);const a=S([t]).values,i=o(this,Se,"m",at).call(this,a,"webhook-signature"),c=o(this,Se,"m",at).call(this,a,"webhook-timestamp"),l=o(this,Se,"m",at).call(this,a,"webhook-id"),u=parseInt(c,10);if(isNaN(u))throw new Re("Invalid webhook timestamp format");const m=Math.floor(Date.now()/1e3);if(m-u>r)throw new Re("Webhook timestamp is too old");if(u>m+r)throw new Re("Webhook timestamp is too new");const h=i.split(" ").map(w=>w.startsWith("v1,")?w.substring(3):w),g=n.startsWith("whsec_")?Buffer.from(n.replace("whsec_",""),"base64"):Buffer.from(n,"utf-8"),d=l?`${l}.${c}.${e}`:`${c}.${e}`,b=await crypto.subtle.importKey("raw",g,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(const w of h)try{const A=Buffer.from(w,"base64");if(await crypto.subtle.verify("HMAC",b,A,new TextEncoder().encode(d)))return}catch{continue}throw new Re("The given webhook signature does not match the expected signature")}}Se=new WeakSet,ar=function(e){if(typeof e!="string"||e.length===0)throw new Error("The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function")},at=function(e,t){if(!e)throw new Error("Headers are required");const n=e.get(t);if(n==null)throw new Error(`Missing required header: ${t}`);return n};var Ut,un,it,or;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(Ut.add(this),it.set(this,void 0),this.completions=new Ws(this),this.chat=new Qt(this),this.embeddings=new qs(this),this.files=new Hs(this),this.images=new zs(this),this.audio=new Ue(this),this.moderations=new Zs(this),this.models=new Ys(this),this.fineTuning=new Ae(this),this.graders=new an(this),this.vectorStores=new bt(this),this.webhooks=new ir(this),this.beta=new qe(this),this.batches=new Ns(this),this.uploads=new ln(this),this.responses=new cn(this),this.evals=new tn(this),this.containers=new Zt(this),t===void 0)throw new I("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 c={apiKey:t,organization:n,project:r,webhookSecret:a,...i,baseURL:e||"https://api.openai.com/v1"};if(!c.dangerouslyAllowBrowser&&Ar())throw new I(`It looks like you're running in a browser-like environment.
15
-
16
- This is disabled by default, as it risks exposing your secret API credentials to attackers.
17
- If you understand the risks and have appropriate mitigations in place,
18
- you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
19
-
20
- new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
21
-
22
- https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
23
- `);this.baseURL=c.baseURL,this.timeout=c.timeout??un.DEFAULT_TIMEOUT,this.logger=c.logger??console;const l="warn";this.logLevel=l,this.logLevel=xn(c.logLevel,"ClientOptions.logLevel",this)??xn(ge("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??l,this.fetchOptions=c.fetchOptions,this.maxRetries=c.maxRetries??2,this.fetch=c.fetch??kr(),C(this,it,Or),this._options=c,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}){}async authHeaders(e){return S([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return jr(e,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${we}`}defaultIdempotencyKey(){return`stainless-node-retry-${Dn()}`}makeStatusError(e,t,n,r){return H.generate(e,t,n,r)}buildURL(e,t,n){const r=!o(this,Ut,"m",or).call(this)&&n||this.baseURL,a=_r(e)?new URL(e):new URL(r+(r.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),i=this.defaultQuery();return wr(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 gt(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,n){var O,p;const r=await e,a=r.maxRetries??this.maxRetries;t==null&&(t=a),await this.prepareOptions(r);const{req:i,url:c,timeout:l}=await this.buildRequest(r,{retryCount:a-t});await this.prepareRequest(i,{url:c,options:r});const u="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),m=n===void 0?"":`, retryOf: ${n}`,h=Date.now();if(q(this).debug(`[${u}] sending request`,le({retryOfRequestLogID:n,method:r.method,url:c,options:r,headers:i.headers})),(O=r.signal)!=null&&O.aborted)throw new z;const g=new AbortController,d=await this.fetchWithTimeout(c,i,l,g).catch(Et),b=Date.now();if(d instanceof Error){const y=`retrying, ${t} attempts remaining`;if((p=r.signal)!=null&&p.aborted)throw new z;const _=Ot(d)||/timed? ?out/i.test(String(d)+("cause"in d?String(d.cause):""));if(t)return q(this).info(`[${u}] connection ${_?"timed out":"failed"} - ${y}`),q(this).debug(`[${u}] connection ${_?"timed out":"failed"} (${y})`,le({retryOfRequestLogID:n,url:c,durationMs:b-h,message:d.message})),this.retryRequest(r,t,n??u);throw q(this).info(`[${u}] connection ${_?"timed out":"failed"} - error; no more retries left`),q(this).debug(`[${u}] connection ${_?"timed out":"failed"} (error; no more retries left)`,le({retryOfRequestLogID:n,url:c,durationMs:b-h,message:d.message})),_?new qt:new mt({cause:d})}const w=[...d.headers.entries()].filter(([y])=>y==="x-request-id").map(([y,_])=>", "+y+": "+JSON.stringify(_)).join(""),A=`[${u}${m}${w}] ${i.method} ${c} ${d.ok?"succeeded":"failed"} with status ${d.status} in ${b-h}ms`;if(!d.ok){const y=await this.shouldRetry(d);if(t&&y){const x=`retrying, ${t} attempts remaining`;return await $r(d.body),q(this).info(`${A} - ${x}`),q(this).debug(`[${u}] response error (${x})`,le({retryOfRequestLogID:n,url:d.url,status:d.status,headers:d.headers,durationMs:b-h})),this.retryRequest(r,t,n??u,d.headers)}const _=y?"error; no more retries left":"error; not retryable";q(this).info(`${A} - ${_}`);const v=await d.text().catch(x=>Et(x).message),$=xr(v),R=$?void 0:v;throw q(this).debug(`[${u}] response error (${_})`,le({retryOfRequestLogID:n,url:d.url,status:d.status,headers:d.headers,message:R,durationMs:Date.now()-h})),this.makeStatusError(d.status,$,R,d.headers)}return q(this).info(A),q(this).debug(`[${u}] response start`,le({retryOfRequestLogID:n,url:d.url,status:d.status,headers:d.headers,durationMs:b-h})),{response:d,options:r,controller:g,requestLogID:u,retryOfRequestLogID:n,startTime:h}}getAPIList(e,t,n){return this.requestAPIList(t,{method:"get",path:e,...n})}requestAPIList(e,t){const n=this.makeRequest(t,null,void 0);return new Hr(this,n,e)}async fetchWithTimeout(e,t,n,r){const{signal:a,method:i,...c}=t||{};a&&a.addEventListener("abort",()=>r.abort());const l=setTimeout(()=>r.abort(),n),u=globalThis.ReadableStream&&c.body instanceof globalThis.ReadableStream||typeof c.body=="object"&&c.body!==null&&Symbol.asyncIterator in c.body,m={signal:r.signal,...u?{duplex:"half"}:{},method:"GET",...c};i&&(m.method=i.toUpperCase());try{return await this.fetch.call(void 0,e,m)}finally{clearTimeout(l)}}async shouldRetry(e){const t=e.headers.get("x-should-retry");return t==="true"?!0:t==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,n,r){let a;const i=r==null?void 0:r.get("retry-after-ms");if(i){const l=parseFloat(i);Number.isNaN(l)||(a=l)}const c=r==null?void 0:r.get("retry-after");if(c&&!a){const l=parseFloat(c);Number.isNaN(l)?a=Date.parse(c)-Date.now():a=l*1e3}if(!(a&&0<=a&&a<60*1e3)){const l=e.maxRetries??this.maxRetries;a=this.calculateDefaultRetryTimeoutMillis(t,l)}return await Be(a),this.makeRequest(e,t-1,n)}calculateDefaultRetryTimeoutMillis(e,t){const a=t-e,i=Math.min(.5*Math.pow(2,a),8),c=1-Math.random()*.25;return i*c*1e3}async buildRequest(e,{retryCount:t=0}={}){const n={...e},{method:r,path:a,query:i,defaultBaseURL:c}=n,l=this.buildURL(a,i,c);"timeout"in n&&Sr("timeout",n.timeout),n.timeout=n.timeout??this.timeout;const{bodyHeaders:u,body:m}=this.buildBody({options:n}),h=await this.buildHeaders({options:e,method:r,bodyHeaders:u,retryCount:t});return{req:{method:r,headers:h,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&m instanceof globalThis.ReadableStream&&{duplex:"half"},...m&&{body:m},...this.fetchOptions??{},...n.fetchOptions??{}},url:l,timeout:n.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:n,retryCount:r}){let a={};this.idempotencyHeader&&t!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),a[this.idempotencyHeader]=e.idempotencyKey);const i=S([a,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(r),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...Rr(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(i),i.values}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};const n=S([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&n.values.has("content-type")||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:zn(e)}:o(this,it,"f").call(this,{body:e,headers:n})}}un=P,it=new WeakMap,Ut=new WeakSet,or=function(){return this.baseURL!=="https://api.openai.com/v1"};P.OpenAI=un;P.DEFAULT_TIMEOUT=6e5;P.OpenAIError=I;P.APIError=H;P.APIConnectionError=mt;P.APIConnectionTimeoutError=qt;P.APIUserAbortError=z;P.NotFoundError=qn;P.ConflictError=Jn;P.RateLimitError=Xn;P.BadRequestError=Bn;P.AuthenticationError=Wn;P.InternalServerError=Kn;P.PermissionDeniedError=Un;P.UnprocessableEntityError=Hn;P.InvalidWebhookSignatureError=Re;P.toFile=zr;P.Completions=Ws;P.Chat=Qt;P.Embeddings=qs;P.Files=Hs;P.Images=zs;P.Audio=Ue;P.Moderations=Zs;P.Models=Ys;P.FineTuning=Ae;P.Graders=an;P.VectorStores=bt;P.Webhooks=ir;P.Beta=qe;P.Batches=Ns;P.Uploads=ln;P.Responses=cn;P.Evals=tn;P.Containers=Zt;const Aa=hr(()=>import("./docs-BrInh2Pn.js"),[],import.meta.url);let ze=null;async function va(s){if(ze)return ze;const e=await s.getObjectViewSystem("state","","香"),t=await s.getObjectViewSystem("channel","","香"),n=await s.getObjectViewSystem("device","","香"),r=await s.getObjectViewSystem("folder","","香"),a=await s.getObjectViewSystem("enum","","香");return ze=Object.assign(e,t,n,r,a),ze}function ye(s,e){return s&&typeof s=="object"?s[e]||s.en:s||""}async function Ca(s){var b,w,A,O;const e=U.I18n.getLanguage(),t=await va(s),n=Object.keys(t).sort(),r=new dr,a=[],i=["UNREACH_STICKY"],c=[fr.Types.info],l=[],u=[],m=[],h=[];n.forEach(p=>{var y,_,v;((y=t[p])==null?void 0:y.type)==="enum"?l.push(p):(v=(_=t[p])==null?void 0:_.common)!=null&&v.smartName&&h.push(p)}),l.forEach(p=>{p.startsWith("enum.rooms.")?u.push(p):p.startsWith("enum.functions.")&&m.push(p);const y=t[p].common.members;y!=null&&y.length&&y.forEach(_=>{t[_]&&(h.includes(_)||h.push(_))})});const g={id:"",objects:t,_keysOptional:n,_usedIdsOptional:a,ignoreIndicators:i,excludedTypes:c},d=[];h.forEach(p=>{g.id=p;const y=r.detect(g);y&&y.forEach(_=>{var me;const v=(me=_.states.find(N=>N.id))==null?void 0:me.id;if(!v||d.find(N=>N.id===v))return;const $=t[v],R={id:v,name:ye($.common.name,e),type:$.type,deviceType:_.type,states:_.states.filter(N=>N.id).map(N=>({id:N.id,name:N.name,role:N.defaultRole,type:t[N.id].common.type,unit:t[N.id].common.unit,read:t[N.id].common.read===void 0?!0:t[N.id].common.read,write:t[N.id].common.write===void 0?!0:t[N.id].common.write}))},F=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=u.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&&(R.room=ye(t[M].common.name,e));const se=m.find(N=>{var ie,ve,Ce;return(ie=t[N].common.members)!=null&&ie.includes(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&&(R.function=ye(t[se].common.name,e)),d.push(R)})});for(let p=0;p<d.length;p++){const y=d[p];if(y.type==="state"||y.type==="channel"){const _=y.id.split(".");_.pop();const v=t[_.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),_.pop();const $=t[_.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(((O=v==null?void 0:v.common)==null?void 0:O.name)||y.name,e)}}return d}const Ia=async()=>(await Aa).default,Ra={ru:"Russian",en:"English",de:"German",es:"Spanish",fr:"French",it:"Italian",pl:"Polish",nl:"Dutch",pt:"Portuguese",uk:"Ukrainian","zh-cn":"Chinese"},Ha=s=>{const[e,t]=Z.useState(window.localStorage.getItem("openai-question")||""),[n,r]=Z.useState(""),[a,i]=Z.useState(!1),[c,l]=Z.useState(!1),[u,m]=Z.useState(window.localStorage.getItem("openai-model")||"gpt-4o"),[h,g]=Z.useState(!1),d=Z.useRef(null),b=Z.useRef(null),w=Z.useRef(null),A=Z.useCallback(async()=>{var _;let O;d.current?O=d.current:(O=await Ca(s.socket),d.current=O,console.log(`devices: ${JSON.stringify(O,null,2)}`));let p;if(b.current)p=b.current;else{const v=Object.keys(s.runningInstances);for(let $=0;$<v.length;$++){const R=await s.socket.getObject(v[$]);if(p=((R==null?void 0:R.native.gptKey)||"").trim(),p)break}b.current=p||null}let y;if(w.current?y=w.current:(y=await Ia(),w.current=y),!p){g(!0);return}i(!0),l(!1);try{const R=(await new P({apiKey:p,dangerouslyAllowBrowser:!0}).chat.completions.create({model:u,messages:[{role:"system",content:`You are programmer. Here is a documentation:
24
-
25
- ${y}`},{role:"system",content:`Here is list of devices:
26
-
27
- ${JSON.stringify(O,null,2)}`},{role:"user",content:`Write JavaScript code that does:
28
-
29
- ${e}
30
- Return only code.
31
- Write comments in ${Ra[U.I18n.getLanguage()]||"English"}.
32
- You can call async function directly in the code without encapsulate them in async function as this code will be already executed in async function.
33
- Do not import any libraries as all functions are already imported.`}]})).choices[0].message,F=(_=R.content)==null?void 0:_.match(/```(javascript|js|typescript)\n?(.*)```(.*)/ms);let x;if(!F)x=R.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(`
34
- `).map(M=>M.trim());for(;T[0]==="";)T.shift();x=`${T.map(M=>`// ${M}`).join(`
35
- `)}
36
- ${x}`}console.log(R),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,u,s.runningInstances,s.socket]);return E.jsxs(j.Dialog,{maxWidth:"lg",sx:{"& .MuiDialog-paper":{height:"calc(100% - 100px)"}},open:!0,onClose:()=>s.onClose(),fullWidth:!0,children:[h&&E.jsxs(j.Dialog,{maxWidth:"lg",open:!0,onClose:()=>g(!1),fullWidth:!0,children:[E.jsx(j.DialogTitle,{children:U.I18n.t("No Chat GPT Key found")}),E.jsxs(j.DialogContent,{style:{display:"flex",flexDirection:"column",gap:8},children:[E.jsx("div",{children:U.I18n.t("You have to enter OpenAI API key in the configuration of javascript adapter.")}),E.jsx(j.Button,{variant:"contained",onClick:()=>{const O=Object.keys(s.runningInstances);window.open(`../../#tab-instances/config/${O[0]||"system.adapter.javascript.0"}`,"_blank"),g(!1)},children:U.I18n.t("Open configuration")})]}),E.jsx(j.DialogActions,{children:E.jsx(j.Button,{variant:"contained",startIcon:E.jsx(hn,{}),onClick:()=>g(!1),children:U.I18n.t("Close")})})]}),E.jsx(j.DialogTitle,{children:U.I18n.t("AI code generator")}),E.jsxs(j.DialogContent,{style:{display:"flex",flexDirection:"column",gap:8,height:"100%"},children:[E.jsx("div",{children:E.jsx(j.TextField,{variant:"standard",multiline:!0,autoFocus:!0,disabled:a,fullWidth:!0,onKeyUp:O=>{O.key==="Enter"&&O.ctrlKey&&A()},label:U.I18n.t("Enter your question"),helperText:U.I18n.t("Press Ctrl+Enter to get the answer"),value:e,onChange:O=>{window.localStorage.setItem("openai-question",O.target.value),t(O.target.value)}})}),E.jsxs("div",{style:{display:"flex",alignItems:"baseline"},children:[E.jsx(j.Button,{variant:"contained",disabled:a||!e,startIcon:E.jsx(pr,{}),onClick:async()=>A(),children:a?E.jsx(j.CircularProgress,{size:24}):U.I18n.t("Ask")}),E.jsxs(j.FormControl,{style:{width:150,marginLeft:20},variant:"standard",children:[E.jsx(j.InputLabel,{children:U.I18n.t("Model")}),E.jsxs(j.Select,{variant:"standard",value:u,onChange:O=>{window.localStorage.setItem("openai-model",O.target.value),c&&l(!1),m(O.target.value)},children:[E.jsx(j.MenuItem,{value:"gpt-4o",children:"GPT-4o"}),E.jsx(j.MenuItem,{value:"gpt-4-turbo",children:"GPT-4 Turbo"}),E.jsx(j.MenuItem,{value:"gpt-4-32k",children:"GPT-4 32k"}),E.jsx(j.MenuItem,{value:"gpt-4",children:"GPT-4"}),E.jsx(j.MenuItem,{value:"gpt-3.5-turbo-16k",children:"GPT-3.5 Turbo"})]})]})]}),E.jsx("div",{children:U.I18n.t("Result")}),E.jsx("div",{style:{height:"calc(100% - 155px)"},children:c?E.jsx("div",{style:{color:s.themeType==="dark"?"#984242":"#bb0000"},children:c}):E.jsx(mr,{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"})})]}),E.jsxs(j.DialogActions,{children:[E.jsx(j.Button,{color:"grey",variant:"outlined",disabled:!n,startIcon:E.jsx(ur,{}),onClick:()=>{U.Utils.copyToClipboard(n),window.alert(U.I18n.t("Copied"))},children:U.I18n.t("Copy to clipboard")}),E.jsx(j.Button,{color:"primary",variant:"contained",disabled:!n||c,startIcon:E.jsx(lr,{}),onClick:()=>{s.onAddCode(n),s.onClose()},children:U.I18n.t("Use generated code")}),E.jsx(j.Button,{color:"grey",variant:"contained",startIcon:E.jsx(hn,{}),onClick:()=>s.onClose(),children:U.I18n.t("Close")})]})]})};export{Ha as default};
@@ -1,2 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["../remoteEntry.js","./iobroker_javascript__mf_v__runtimeInit__mf_v__-CmuPLb0X.js","./virtualExposes-BIHI7g3E.js","./preload-helper-Dp1pzeXC.js"])))=>i.map(i=>d[i]);
2
- import{_ as i}from"./preload-helper-Dp1pzeXC.js";const r=i(()=>import("../remoteEntry.js"),__vite__mapDeps([0,1,2,3]),import.meta.url);Promise.resolve(r).then(e=>Promise.resolve(e.__tla).then(e.init).catch(e.init));