@slycode/slycode 0.2.5 → 0.2.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (172) hide show
  1. package/dist/messaging/index.js +9 -2
  2. package/dist/messaging/index.js.map +1 -1
  3. package/dist/messaging/stt.d.ts +3 -1
  4. package/dist/messaging/stt.js +76 -0
  5. package/dist/messaging/stt.js.map +1 -1
  6. package/dist/messaging/types.d.ts +3 -1
  7. package/dist/scripts/scaffold.js +3 -2
  8. package/dist/web/.next/BUILD_ID +1 -1
  9. package/dist/web/.next/build-manifest.json +4 -4
  10. package/dist/web/.next/server/app/_global-error/page/build-manifest.json +2 -2
  11. package/dist/web/.next/server/app/_global-error/page.js +1 -1
  12. package/dist/web/.next/server/app/_global-error/page.js.nft.json +1 -1
  13. package/dist/web/.next/server/app/_global-error.html +2 -2
  14. package/dist/web/.next/server/app/_global-error.rsc +1 -1
  15. package/dist/web/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +1 -1
  16. package/dist/web/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  17. package/dist/web/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
  18. package/dist/web/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
  19. package/dist/web/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  20. package/dist/web/.next/server/app/_not-found/page/build-manifest.json +2 -2
  21. package/dist/web/.next/server/app/_not-found/page.js +1 -1
  22. package/dist/web/.next/server/app/_not-found/page.js.nft.json +1 -1
  23. package/dist/web/.next/server/app/_not-found.html +1 -1
  24. package/dist/web/.next/server/app/_not-found.rsc +1 -1
  25. package/dist/web/.next/server/app/_not-found.segments/_full.segment.rsc +1 -1
  26. package/dist/web/.next/server/app/_not-found.segments/_head.segment.rsc +1 -1
  27. package/dist/web/.next/server/app/_not-found.segments/_index.segment.rsc +1 -1
  28. package/dist/web/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
  29. package/dist/web/.next/server/app/_not-found.segments/_not-found.segment.rsc +1 -1
  30. package/dist/web/.next/server/app/_not-found.segments/_tree.segment.rsc +1 -1
  31. package/dist/web/.next/server/app/api/cli-assets/fix/route.js +1 -1
  32. package/dist/web/.next/server/app/api/cli-assets/fix/route.js.nft.json +1 -1
  33. package/dist/web/.next/server/app/api/cli-assets/import/route.js +1 -1
  34. package/dist/web/.next/server/app/api/cli-assets/import/route.js.nft.json +1 -1
  35. package/dist/web/.next/server/app/api/cli-assets/route.js +1 -1
  36. package/dist/web/.next/server/app/api/cli-assets/route.js.nft.json +1 -1
  37. package/dist/web/.next/server/app/api/cli-assets/store/preview/route.js +1 -1
  38. package/dist/web/.next/server/app/api/cli-assets/store/preview/route.js.nft.json +1 -1
  39. package/dist/web/.next/server/app/api/cli-assets/store/route.js +1 -1
  40. package/dist/web/.next/server/app/api/cli-assets/store/route.js.nft.json +1 -1
  41. package/dist/web/.next/server/app/api/cli-assets/sync/route.js +1 -1
  42. package/dist/web/.next/server/app/api/cli-assets/sync/route.js.nft.json +1 -1
  43. package/dist/web/.next/server/app/api/cli-assets/updates/route.js +1 -1
  44. package/dist/web/.next/server/app/api/cli-assets/updates/route.js.nft.json +1 -1
  45. package/dist/web/.next/server/app/api/dashboard/route.js +1 -1
  46. package/dist/web/.next/server/app/api/dashboard/route.js.nft.json +1 -1
  47. package/dist/web/.next/server/app/api/file/route.js +1 -1
  48. package/dist/web/.next/server/app/api/file/route.js.nft.json +1 -1
  49. package/dist/web/.next/server/app/api/git-status/route.js +1 -1
  50. package/dist/web/.next/server/app/api/git-status/route.js.nft.json +1 -1
  51. package/dist/web/.next/server/app/api/kanban/route.js +1 -1
  52. package/dist/web/.next/server/app/api/kanban/route.js.nft.json +1 -1
  53. package/dist/web/.next/server/app/api/kanban/stream/route.js +1 -1
  54. package/dist/web/.next/server/app/api/kanban/stream/route.js.nft.json +1 -1
  55. package/dist/web/.next/server/app/api/projects/[id]/route.js +1 -1
  56. package/dist/web/.next/server/app/api/projects/[id]/route.js.nft.json +1 -1
  57. package/dist/web/.next/server/app/api/projects/reorder/route.js +1 -1
  58. package/dist/web/.next/server/app/api/projects/reorder/route.js.nft.json +1 -1
  59. package/dist/web/.next/server/app/api/projects/route.js +1 -1
  60. package/dist/web/.next/server/app/api/projects/route.js.nft.json +1 -1
  61. package/dist/web/.next/server/app/api/scheduler/route.js +1 -1
  62. package/dist/web/.next/server/app/api/scheduler/route.js.nft.json +1 -1
  63. package/dist/web/.next/server/app/api/search/route.js +1 -1
  64. package/dist/web/.next/server/app/api/search/route.js.nft.json +1 -1
  65. package/dist/web/.next/server/app/api/sly-actions/invalidate/route.js +1 -1
  66. package/dist/web/.next/server/app/api/sly-actions/invalidate/route.js.nft.json +1 -1
  67. package/dist/web/.next/server/app/api/sly-actions/route.js +1 -1
  68. package/dist/web/.next/server/app/api/sly-actions/route.js.nft.json +1 -1
  69. package/dist/web/.next/server/app/api/sly-actions/stream/route.js +1 -1
  70. package/dist/web/.next/server/app/api/sly-actions/stream/route.js.nft.json +1 -1
  71. package/dist/web/.next/server/app/api/transcribe/route.js +5 -2
  72. package/dist/web/.next/server/app/api/transcribe/route.js.nft.json +1 -1
  73. package/dist/web/.next/server/app/page/build-manifest.json +2 -2
  74. package/dist/web/.next/server/app/page.js +2 -2
  75. package/dist/web/.next/server/app/page.js.nft.json +1 -1
  76. package/dist/web/.next/server/app/page_client-reference-manifest.js +1 -1
  77. package/dist/web/.next/server/app/project/[id]/page/build-manifest.json +2 -2
  78. package/dist/web/.next/server/app/project/[id]/page.js +2 -2
  79. package/dist/web/.next/server/app/project/[id]/page.js.nft.json +1 -1
  80. package/dist/web/.next/server/app/project/[id]/page_client-reference-manifest.js +1 -1
  81. package/dist/web/.next/server/chunks/[externals]__c6831f39._.js +3 -0
  82. package/dist/web/.next/server/chunks/[externals]_node:async_hooks_b485b2a4._.js +3 -0
  83. package/dist/web/.next/server/chunks/[externals]_node:http_c3a9e25f._.js +3 -0
  84. package/dist/web/.next/server/chunks/[root-of-the-server]__0234f869._.js +3 -0
  85. package/dist/web/.next/server/chunks/[root-of-the-server]__0f8687da._.js +3 -0
  86. package/dist/web/.next/server/chunks/[root-of-the-server]__104b2da3._.js +4 -0
  87. package/dist/web/.next/server/chunks/[root-of-the-server]__12f6cd6f._.js +3 -0
  88. package/dist/web/.next/server/chunks/[root-of-the-server]__15fc9266._.js +18 -0
  89. package/dist/web/.next/server/chunks/[root-of-the-server]__1cdc76ef._.js +3 -0
  90. package/dist/web/.next/server/chunks/{[root-of-the-server]__933e6077._.js → [root-of-the-server]__1ec21ccc._.js} +2 -2
  91. package/dist/web/.next/server/chunks/[root-of-the-server]__279e9bf3._.js +3 -0
  92. package/dist/web/.next/server/chunks/[root-of-the-server]__2d1f0ed9._.js +3 -0
  93. package/dist/web/.next/server/chunks/[root-of-the-server]__3998d59e._.js +19 -0
  94. package/dist/web/.next/server/chunks/[root-of-the-server]__3c5ef8ec._.js +3 -0
  95. package/dist/web/.next/server/chunks/[root-of-the-server]__3dc5531f._.js +5 -0
  96. package/dist/web/.next/server/chunks/[root-of-the-server]__403750fd._.js +3 -0
  97. package/dist/web/.next/server/chunks/[root-of-the-server]__41df0777._.js +3 -0
  98. package/dist/web/.next/server/chunks/{[root-of-the-server]__b9e7d34c._.js → [root-of-the-server]__4244617a._.js} +2 -2
  99. package/dist/web/.next/server/chunks/[root-of-the-server]__47dd878e._.js +3 -0
  100. package/dist/web/.next/server/chunks/[root-of-the-server]__5e08b942._.js +3 -0
  101. package/dist/web/.next/server/chunks/[root-of-the-server]__71bb3374._.js +3 -0
  102. package/dist/web/.next/server/chunks/[root-of-the-server]__7603305e._.js +3 -0
  103. package/dist/web/.next/server/chunks/[root-of-the-server]__7c476ad6._.js +3 -0
  104. package/dist/web/.next/server/chunks/[root-of-the-server]__846ca56f._.js +3 -0
  105. package/dist/web/.next/server/chunks/[root-of-the-server]__934c9bb4._.js +5 -0
  106. package/dist/web/.next/server/chunks/[root-of-the-server]__98d88050._.js +3 -0
  107. package/dist/web/.next/server/chunks/[root-of-the-server]__b273cc05._.js +3 -0
  108. package/dist/web/.next/server/chunks/{[root-of-the-server]__bc55c42a._.js → [root-of-the-server]__d0f4efec._.js} +2 -2
  109. package/dist/web/.next/server/chunks/[root-of-the-server]__d6362272._.js +3 -0
  110. package/dist/web/.next/server/chunks/[root-of-the-server]__de1277ee._.js +27 -0
  111. package/dist/web/.next/server/chunks/[root-of-the-server]__e00fb85f._.js +9 -0
  112. package/dist/web/.next/server/chunks/[root-of-the-server]__e4988941._.js +4 -0
  113. package/dist/web/.next/server/chunks/[root-of-the-server]__f3e501b6._.js +3 -0
  114. package/dist/web/.next/server/chunks/[root-of-the-server]__f97e93fa._.js +6 -0
  115. package/dist/web/.next/server/chunks/a9bf9_@aws-sdk_core_dist-es_submodules_protocols_json_AwsRestJsonProtocol_764d7a83.js +3 -0
  116. package/dist/web/.next/server/chunks/node_modules_@aws-sdk_credential-provider-env_dist-es_index_55d96139.js +3 -0
  117. package/dist/web/.next/server/chunks/node_modules_@aws-sdk_nested-clients_dist-es_submodules_signin_index_6712dec9.js +3 -0
  118. package/dist/web/.next/server/chunks/node_modules_@aws-sdk_nested-clients_dist-es_submodules_sso-oidc_index_df09d547.js +3 -0
  119. package/dist/web/.next/server/chunks/node_modules_@aws-sdk_nested-clients_dist-es_submodules_sts_index_c78619b3.js +3 -0
  120. package/dist/web/.next/server/chunks/node_modules_@smithy_core_dist-es_submodules_event-streams_index_73e35402.js +3 -0
  121. package/dist/web/.next/server/chunks/node_modules_ec9ae6c4._.js +18 -0
  122. package/dist/web/.next/server/chunks/src_677020aa._.js +1 -1
  123. package/dist/web/.next/server/chunks/ssr/[root-of-the-server]__077f472c._.js +3 -0
  124. package/dist/web/.next/server/chunks/ssr/{[root-of-the-server]__977b1a68._.js → [root-of-the-server]__0841f0b5._.js} +2 -2
  125. package/dist/web/.next/server/chunks/ssr/[root-of-the-server]__1f5fc489._.js +9 -0
  126. package/dist/web/.next/server/chunks/ssr/[root-of-the-server]__2f64210a._.js +3 -0
  127. package/dist/web/.next/server/chunks/ssr/{[root-of-the-server]__d57c94e0._.js → [root-of-the-server]__92021d33._.js} +2 -2
  128. package/dist/web/.next/server/chunks/ssr/{[root-of-the-server]__e0032864._.js → [root-of-the-server]__9ac6ea25._.js} +2 -2
  129. package/dist/web/.next/server/chunks/ssr/{[root-of-the-server]__677b7660._.js → [root-of-the-server]__bcbe4bf2._.js} +2 -2
  130. package/dist/web/.next/server/chunks/ssr/{[root-of-the-server]__6db27fe1._.js → [root-of-the-server]__dfe2728c._.js} +2 -2
  131. package/dist/web/.next/server/chunks/ssr/src_lib_registry_ts_2fc87c9c._.js +1 -1
  132. package/dist/web/.next/server/middleware-build-manifest.js +2 -2
  133. package/dist/web/.next/server/pages/404.html +1 -1
  134. package/dist/web/.next/server/pages/500.html +2 -2
  135. package/dist/web/.next/static/chunks/0bab8c7c82cef548.js +4 -0
  136. package/dist/web/.next/static/chunks/{b694f741bb34ac84.js → 1b46e836090e130b.js} +1 -1
  137. package/dist/web/.next/static/chunks/{ef0dc6461e9250d8.js → cf910fc299170b7d.js} +2 -2
  138. package/dist/web/.next/static/chunks/{turbopack-4964158913ad5e72.js → turbopack-563e27abda63930f.js} +2 -2
  139. package/dist/web/package-lock.json +1589 -155
  140. package/dist/web/package.json +1 -0
  141. package/dist/web/src/app/api/transcribe/route.ts +96 -1
  142. package/dist/web/src/lib/store-scanner.ts +8 -69
  143. package/dist/web/tsconfig.tsbuildinfo +1 -1
  144. package/package.json +1 -1
  145. package/templates/kanban-seed.json +1 -1
  146. package/dist/web/.next/server/chunks/[externals]__65615fd8._.js +0 -3
  147. package/dist/web/.next/server/chunks/[root-of-the-server]__46b023d4._.js +0 -3
  148. package/dist/web/.next/server/chunks/[root-of-the-server]__4c7995bf._.js +0 -3
  149. package/dist/web/.next/server/chunks/[root-of-the-server]__4d0d3464._.js +0 -3
  150. package/dist/web/.next/server/chunks/[root-of-the-server]__6d330d40._.js +0 -3
  151. package/dist/web/.next/server/chunks/[root-of-the-server]__884d73e4._.js +0 -3
  152. package/dist/web/.next/server/chunks/[root-of-the-server]__8ab096a3._.js +0 -3
  153. package/dist/web/.next/server/chunks/[root-of-the-server]__9058a007._.js +0 -3
  154. package/dist/web/.next/server/chunks/[root-of-the-server]__949bb248._.js +0 -3
  155. package/dist/web/.next/server/chunks/[root-of-the-server]__aa814a86._.js +0 -3
  156. package/dist/web/.next/server/chunks/[root-of-the-server]__ad64e04f._.js +0 -27
  157. package/dist/web/.next/server/chunks/[root-of-the-server]__baa99257._.js +0 -3
  158. package/dist/web/.next/server/chunks/[root-of-the-server]__bbb4b3ac._.js +0 -3
  159. package/dist/web/.next/server/chunks/[root-of-the-server]__bf286c26._.js +0 -3
  160. package/dist/web/.next/server/chunks/[root-of-the-server]__d219e3f0._.js +0 -18
  161. package/dist/web/.next/server/chunks/[root-of-the-server]__d38c7a96._.js +0 -3
  162. package/dist/web/.next/server/chunks/[root-of-the-server]__e9b0e744._.js +0 -3
  163. package/dist/web/.next/server/chunks/[root-of-the-server]__f1fe18e6._.js +0 -6
  164. package/dist/web/.next/server/chunks/[root-of-the-server]__f4124388._.js +0 -3
  165. package/dist/web/.next/server/chunks/node_modules_next_dist_esm_build_templates_app-route_ffc6c790.js +0 -11
  166. package/dist/web/.next/server/chunks/ssr/[root-of-the-server]__73cfc6bb._.js +0 -3
  167. package/dist/web/.next/server/chunks/ssr/[root-of-the-server]__79c0188d._.js +0 -9
  168. package/dist/web/.next/server/chunks/ssr/[root-of-the-server]__bb807bcf._.js +0 -3
  169. package/dist/web/.next/static/chunks/7660448872d80e27.js +0 -4
  170. /package/dist/web/.next/static/{Ky5DLflBRa2FbKsyhH40R → LL2KFMFJkFiDQbYtgqSpv}/_buildManifest.js +0 -0
  171. /package/dist/web/.next/static/{Ky5DLflBRa2FbKsyhH40R → LL2KFMFJkFiDQbYtgqSpv}/_clientMiddlewareManifest.json +0 -0
  172. /package/dist/web/.next/static/{Ky5DLflBRa2FbKsyhH40R → LL2KFMFJkFiDQbYtgqSpv}/_ssgManifest.js +0 -0
@@ -1,11 +0,0 @@
1
- module.exports=[99567,e=>{"use strict";let t,s,n,r;var i,a,o,l,c,u,h,d,p,f,m,g,_,w,y,b,v,x,S,$,A,R,I,O,E,k,P,C,T,N,j,M,D,L,B,W,q,U,H,F,X,K,J,V,z,G,Q,Y,Z,ee,et,es,en,er,ei,ea,eo,el,ec,eu,eh,ed,ep,ef,em,eg,e_,ew,ey,eb,ev,ex,eS,e$,eA,eR,eI=e.i(47909),eO=e.i(74017),eE=e.i(96250),ek=e.i(59756),eP=e.i(61916),eC=e.i(74677),eT=e.i(69741),eN=e.i(16795),ej=e.i(87718),eM=e.i(95169),eD=e.i(47587),eL=e.i(66012),eB=e.i(70101),eW=e.i(74838),eq=e.i(10372),eU=e.i(93695);e.i(52474);var eH=e.i(220),eF=e.i(89171);function eX(e,t,s,n,r){if("m"===n)throw TypeError("Private method is not writable");if("a"===n&&!r)throw TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,s):r?r.value=s:t.set(e,s),s}function eK(e,t,s,n){if("a"===s&&!n)throw TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw TypeError("Cannot read private member from an object whose class did not declare it");return"m"===s?n:"a"===s?n.call(e):n?n.value:t.get(e)}let eJ=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return eJ=e.randomUUID.bind(e),e.randomUUID();let t=new Uint8Array(1),s=e?()=>e.getRandomValues(t)[0]:()=>255*Math.random()&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,e=>(e^s()&15>>e/4).toString(16))};function eV(e){return"object"==typeof e&&null!==e&&("name"in e&&"AbortError"===e.name||"message"in e&&String(e.message).includes("FetchRequestCanceledException"))}let ez=e=>{if(e instanceof Error)return e;if("object"==typeof e&&null!==e){try{if("[object Error]"===Object.prototype.toString.call(e)){let t=Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch{}try{return Error(JSON.stringify(e))}catch{}}return Error(e)};class eG extends Error{}class eQ extends eG{constructor(e,t,s,n){super(`${eQ.makeMessage(e,t,s)}`),this.status=e,this.headers=n,this.requestID=n?.get("x-request-id"),this.error=t,this.code=t?.code,this.param=t?.param,this.type=t?.type}static makeMessage(e,t,s){let n=t?.message?"string"==typeof t.message?t.message:JSON.stringify(t.message):t?JSON.stringify(t):s;return e&&n?`${e} ${n}`:e?`${e} status code (no body)`:n||"(no status code or body)"}static generate(e,t,s,n){if(!e||!n)return new eZ({message:s,cause:ez(t)});let r=t?.error;return 400===e?new e1(e,r,s,n):401===e?new e2(e,r,s,n):403===e?new e4(e,r,s,n):404===e?new e6(e,r,s,n):409===e?new e3(e,r,s,n):422===e?new e8(e,r,s,n):429===e?new e5(e,r,s,n):e>=500?new e9(e,r,s,n):new eQ(e,r,s,n)}}class eY extends eQ{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class eZ extends eQ{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}}class e0 extends eZ{constructor({message:e}={}){super({message:e??"Request timed out."})}}class e1 extends eQ{}class e2 extends eQ{}class e4 extends eQ{}class e6 extends eQ{}class e3 extends eQ{}class e8 extends eQ{}class e5 extends eQ{}class e9 extends eQ{}class e7 extends eG{constructor(){super("Could not parse response content as the length limit was reached")}}class te extends eG{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class tt extends Error{constructor(e){super(e)}}let ts=/^[a-z][a-z0-9+.-]*:/i,tn=e=>(tn=Array.isArray)(e),tr=tn;function ti(e){return"object"!=typeof e?{}:e??{}}function ta(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)}let to=e=>new Promise(t=>setTimeout(t,e)),tl="6.23.0",tc=e=>"x32"===e?"x32":"x86_64"===e||"x64"===e?"x64":"arm"===e?"arm":"aarch64"===e||"arm64"===e?"arm64":e?`other:${e}`:"unknown",tu=e=>(e=e.toLowerCase()).includes("ios")?"iOS":"android"===e?"Android":"darwin"===e?"MacOS":"win32"===e?"Windows":"freebsd"===e?"FreeBSD":"openbsd"===e?"OpenBSD":"linux"===e?"Linux":e?`Other:${e}`:"Unknown";function th(...e){let t=globalThis.ReadableStream;if(void 0===t)throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function td(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return th({start(){},async pull(e){let{done:s,value:n}=await t.next();s?e.close():e.enqueue(n)},async cancel(){await t.return?.()}})}function tp(e){if(e[Symbol.asyncIterator])return e;let t=e.getReader();return{async next(){try{let e=await t.read();return e?.done&&t.releaseLock(),e}catch(e){throw t.releaseLock(),e}},async return(){let e=t.cancel();return t.releaseLock(),await e,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function tf(e){if(null===e||"object"!=typeof e)return;if(e[Symbol.asyncIterator])return void await e[Symbol.asyncIterator]().return?.();let t=e.getReader(),s=t.cancel();t.releaseLock(),await s}let tm=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)}),tg="RFC3986",t_=e=>String(e),tw={RFC1738:e=>String(e).replace(/%20/g,"+"),RFC3986:t_},ty=(e,t)=>(ty=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty))(e,t),tb=(()=>{let e=[];for(let t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e})();function tv(e,t){if(tn(e)){let s=[];for(let n=0;n<e.length;n+=1)s.push(t(e[n]));return s}return t(e)}let tx={brackets:e=>String(e)+"[]",comma:"comma",indices:(e,t)=>String(e)+"["+t+"]",repeat:e=>String(e)},tS=function(e,t){Array.prototype.push.apply(e,tn(t)?t:[t])},t$={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:(e,t,s,n,r)=>{if(0===e.length)return e;let i=e;if("symbol"==typeof e?i=Symbol.prototype.toString.call(e):"string"!=typeof e&&(i=String(e)),"iso-8859-1"===s)return escape(i).replace(/%u[0-9a-f]{4}/gi,function(e){return"%26%23"+parseInt(e.slice(2),16)+"%3B"});let a="";for(let e=0;e<i.length;e+=1024){let t=i.length>=1024?i.slice(e,e+1024):i,s=[];for(let e=0;e<t.length;++e){let n=t.charCodeAt(e);if(45===n||46===n||95===n||126===n||n>=48&&n<=57||n>=65&&n<=90||n>=97&&n<=122||"RFC1738"===r&&(40===n||41===n)){s[s.length]=t.charAt(e);continue}if(n<128){s[s.length]=tb[n];continue}if(n<2048){s[s.length]=tb[192|n>>6]+tb[128|63&n];continue}if(n<55296||n>=57344){s[s.length]=tb[224|n>>12]+tb[128|n>>6&63]+tb[128|63&n];continue}e+=1,n=65536+((1023&n)<<10|1023&t.charCodeAt(e)),s[s.length]=tb[240|n>>18]+tb[128|n>>12&63]+tb[128|n>>6&63]+tb[128|63&n]}a+=s.join("")}return a},encodeValuesOnly:!1,format:tg,formatter:t_,indices:!1,serializeDate:e=>(s??(s=Function.prototype.call.bind(Date.prototype.toISOString)))(e),skipNulls:!1,strictNullHandling:!1},tA={};function tR(e){let t;return(n??(n=(t=new globalThis.TextEncoder).encode.bind(t)))(e)}function tI(e){let t;return(r??(r=(t=new globalThis.TextDecoder).decode.bind(t)))(e)}class tO{constructor(){i.set(this,void 0),a.set(this,void 0),eX(this,i,new Uint8Array,"f"),eX(this,a,null,"f")}decode(e){let t;if(null==e)return[];let s=e instanceof ArrayBuffer?new Uint8Array(e):"string"==typeof e?tR(e):e;eX(this,i,function(e){let t=0;for(let s of e)t+=s.length;let s=new Uint8Array(t),n=0;for(let t of e)s.set(t,n),n+=t.length;return s}([eK(this,i,"f"),s]),"f");let n=[];for(;null!=(t=function(e,t){for(let s=t??0;s<e.length;s++){if(10===e[s])return{preceding:s,index:s+1,carriage:!1};if(13===e[s])return{preceding:s,index:s+1,carriage:!0}}return null}(eK(this,i,"f"),eK(this,a,"f")));){if(t.carriage&&null==eK(this,a,"f")){eX(this,a,t.index,"f");continue}if(null!=eK(this,a,"f")&&(t.index!==eK(this,a,"f")+1||t.carriage)){n.push(tI(eK(this,i,"f").subarray(0,eK(this,a,"f")-1))),eX(this,i,eK(this,i,"f").subarray(eK(this,a,"f")),"f"),eX(this,a,null,"f");continue}let e=null!==eK(this,a,"f")?t.preceding-1:t.preceding,s=tI(eK(this,i,"f").subarray(0,e));n.push(s),eX(this,i,eK(this,i,"f").subarray(t.index),"f"),eX(this,a,null,"f")}return n}flush(){return eK(this,i,"f").length?this.decode("\n"):[]}}i=new WeakMap,a=new WeakMap,tO.NEWLINE_CHARS=new Set(["\n","\r"]),tO.NEWLINE_REGEXP=/\r\n|[\n\r]/g;let tE={off:0,error:200,warn:300,info:400,debug:500},tk=(e,t,s)=>{if(e){if(Object.prototype.hasOwnProperty.call(tE,e))return e;tj(s).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(tE))}`)}};function tP(){}function tC(e,t,s){return!t||tE[e]>tE[s]?tP:t[e].bind(t)}let tT={error:tP,warn:tP,info:tP,debug:tP},tN=new WeakMap;function tj(e){let t=e.logger,s=e.logLevel??"off";if(!t)return tT;let n=tN.get(t);if(n&&n[0]===s)return n[1];let r={error:tC("error",t,s),warn:tC("warn",t,s),info:tC("info",t,s),debug:tC("debug",t,s)};return tN.set(t,[s,r]),r}let tM=e=>(e.options&&(e.options={...e.options},delete e.options.headers),e.headers&&(e.headers=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([e,t])=>[e,"authorization"===e.toLowerCase()||"cookie"===e.toLowerCase()||"set-cookie"===e.toLowerCase()?"***":t]))),"retryOfRequestLogID"in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e);class tD{constructor(e,t,s){this.iterator=e,o.set(this,void 0),this.controller=t,eX(this,o,s,"f")}static fromSSEResponse(e,t,s){let n=!1,r=s?tj(s):console;async function*i(){if(n)throw new eG("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let s=!1;try{for await(let n of tL(e,t))if(!s){if(n.data.startsWith("[DONE]")){s=!0;continue}if(null!==n.event&&n.event.startsWith("thread.")){let e;try{e=JSON.parse(n.data)}catch(e){throw console.error("Could not parse message into JSON:",n.data),console.error("From chunk:",n.raw),e}if("error"==n.event)throw new eQ(void 0,e.error,e.message,void 0);yield{event:n.event,data:e}}else{let t;try{t=JSON.parse(n.data)}catch(e){throw r.error("Could not parse message into JSON:",n.data),r.error("From chunk:",n.raw),e}if(t&&t.error)throw new eQ(void 0,t.error,void 0,e.headers);yield t}}s=!0}catch(e){if(eV(e))return;throw e}finally{s||t.abort()}}return new tD(i,t,s)}static fromReadableStream(e,t,s){let n=!1;async function*r(){let t=new tO;for await(let s of tp(e))for(let e of t.decode(s))yield e;for(let e of t.flush())yield e}return new tD(async function*(){if(n)throw new eG("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let e=!1;try{for await(let t of r())!e&&t&&(yield JSON.parse(t));e=!0}catch(e){if(eV(e))return;throw e}finally{e||t.abort()}},t,s)}[(o=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],t=[],s=this.iterator(),n=n=>({next:()=>{if(0===n.length){let n=s.next();e.push(n),t.push(n)}return n.shift()}});return[new tD(()=>n(e),this.controller,eK(this,o,"f")),new tD(()=>n(t),this.controller,eK(this,o,"f"))]}toReadableStream(){let e,t=this;return th({async start(){e=t[Symbol.asyncIterator]()},async pull(t){try{let{value:s,done:n}=await e.next();if(n)return t.close();let r=tR(JSON.stringify(s)+"\n");t.enqueue(r)}catch(e){t.error(e)}},async cancel(){await e.return?.()}})}}async function*tL(e,t){if(!e.body){if(t.abort(),void 0!==globalThis.navigator&&"ReactNative"===globalThis.navigator.product)throw new eG("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api");throw new eG("Attempted to iterate over a response with no body")}let s=new tW,n=new tO;for await(let t of tB(tp(e.body)))for(let e of n.decode(t)){let t=s.decode(e);t&&(yield t)}for(let e of n.flush()){let t=s.decode(e);t&&(yield t)}}async function*tB(e){let t=new Uint8Array;for await(let s of e){let e;if(null==s)continue;let n=s instanceof ArrayBuffer?new Uint8Array(s):"string"==typeof s?tR(s):s,r=new Uint8Array(t.length+n.length);for(r.set(t),r.set(n,t.length),t=r;-1!==(e=function(e){for(let t=0;t<e.length-1;t++){if(10===e[t]&&10===e[t+1]||13===e[t]&&13===e[t+1])return t+2;if(13===e[t]&&10===e[t+1]&&t+3<e.length&&13===e[t+2]&&10===e[t+3])return t+4}return -1}(t));)yield t.slice(0,e),t=t.slice(e)}t.length>0&&(yield t)}class tW{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){var t;let s;if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let e={event:this.event,data:this.data.join("\n"),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],e}if(this.chunks.push(e),e.startsWith(":"))return null;let[n,r,i]=-1!==(s=(t=e).indexOf(":"))?[t.substring(0,s),":",t.substring(s+1)]:[t,"",""];return i.startsWith(" ")&&(i=i.substring(1)),"event"===n?this.event=i:"data"===n&&this.data.push(i),null}}async function tq(e,t){let{response:s,requestLogID:n,retryOfRequestLogID:r,startTime:i}=t,a=await (async()=>{if(t.options.stream)return(tj(e).debug("response",s.status,s.url,s.headers,s.body),t.options.__streamClass)?t.options.__streamClass.fromSSEResponse(s,t.controller,e):tD.fromSSEResponse(s,t.controller,e);if(204===s.status)return null;if(t.options.__binaryResponse)return s;let n=s.headers.get("content-type"),r=n?.split(";")[0]?.trim();if(r?.includes("application/json")||r?.endsWith("+json")){if("0"===s.headers.get("content-length"))return;return tU(await s.json(),s)}return await s.text()})();return tj(e).debug(`[${n}] response parsed`,tM({retryOfRequestLogID:r,url:s.url,status:s.status,body:a,durationMs:Date.now()-i})),a}function tU(e,t){return!e||"object"!=typeof e||Array.isArray(e)?e:Object.defineProperty(e,"_request_id",{value:t.headers.get("x-request-id"),enumerable:!1})}class tH extends Promise{constructor(e,t,s=tq){super(e=>{e(null)}),this.responsePromise=t,this.parseResponse=s,l.set(this,void 0),eX(this,l,e,"f")}_thenUnwrap(e){return new tH(eK(this,l,"f"),this.responsePromise,async(t,s)=>tU(e(await this.parseResponse(t,s),s),s.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[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(eK(this,l,"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)}}l=new WeakMap;class tF{constructor(e,t,s,n){c.set(this,void 0),eX(this,c,e,"f"),this.options=n,this.response=t,this.body=s}hasNextPage(){return!!this.getPaginatedItems().length&&null!=this.nextPageRequestOptions()}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new eG("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await eK(this,c,"f").requestAPIList(this.constructor,e)}async *iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async *[(c=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}}class tX extends tH{constructor(e,t,s){super(e,t,async(e,t)=>new s(e,t.response,await tq(e,t),t.options))}async *[Symbol.asyncIterator](){for await(let e of(await this))yield e}}class tK extends tF{constructor(e,t,s,n){super(e,t,s,n),this.data=s.data||[],this.object=s.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}}class tJ extends tF{constructor(e,t,s,n){super(e,t,s,n),this.data=s.data||[],this.has_more=s.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return!1!==this.has_more&&super.hasNextPage()}nextPageRequestOptions(){let e=this.getPaginatedItems(),t=e[e.length-1]?.id;return t?{...this.options,query:{...ti(this.options.query),after:t}}:null}}class tV extends tF{constructor(e,t,s,n){super(e,t,s,n),this.data=s.data||[],this.has_more=s.has_more||!1,this.last_id=s.last_id||""}getPaginatedItems(){return this.data??[]}hasNextPage(){return!1!==this.has_more&&super.hasNextPage()}nextPageRequestOptions(){let e=this.last_id;return e?{...this.options,query:{...ti(this.options.query),after:e}}:null}}let tz=()=>{if("u"<typeof File){let{process:e}=globalThis;throw Error("`File` is not defined as a global, which is required for file uploads."+("string"==typeof e?.versions?.node&&20>parseInt(e.versions.node.split("."))?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function tG(e,t,s){return tz(),new File(e,t??"unknown_file",s)}function tQ(e){return("object"==typeof e&&null!==e&&("name"in e&&e.name&&String(e.name)||"url"in e&&e.url&&String(e.url)||"filename"in e&&e.filename&&String(e.filename)||"path"in e&&e.path&&String(e.path))||"").split(/[\\/]/).pop()||void 0}let tY=e=>null!=e&&"object"==typeof e&&"function"==typeof e[Symbol.asyncIterator],tZ=async(e,t)=>t6(e.body)?{...e,body:await t2(e.body,t)}:e,t0=async(e,t)=>({...e,body:await t2(e.body,t)}),t1=new WeakMap,t2=async(e,t)=>{if(!await function(e){let t="function"==typeof e?e:e.fetch,s=t1.get(t);if(s)return s;let n=(async()=>{try{let e="Response"in t?t.Response:(await t("data:,")).constructor,s=new FormData;if(s.toString()===await new e(s).text())return!1;return!0}catch{return!0}})();return t1.set(t,n),n}(t))throw TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let s=new FormData;return await Promise.all(Object.entries(e||{}).map(([e,t])=>t3(s,e,t))),s},t4=e=>e instanceof Blob&&"name"in e,t6=e=>{if("object"==typeof e&&null!==e&&(e instanceof Response||tY(e)||t4(e)))return!0;if(Array.isArray(e))return e.some(t6);if(e&&"object"==typeof e){for(let t in e)if(t6(e[t]))return!0}return!1},t3=async(e,t,s)=>{if(void 0!==s){if(null==s)throw TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if("string"==typeof s||"number"==typeof s||"boolean"==typeof s)e.append(t,String(s));else if(s instanceof Response)e.append(t,tG([await s.blob()],tQ(s)));else if(tY(s))e.append(t,tG([await new Response(td(s)).blob()],tQ(s)));else if(t4(s))e.append(t,s,tQ(s));else if(Array.isArray(s))await Promise.all(s.map(s=>t3(e,t+"[]",s)));else if("object"==typeof s)await Promise.all(Object.entries(s).map(([s,n])=>t3(e,`${t}[${s}]`,n)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${s} instead`)}},t8=e=>null!=e&&"object"==typeof e&&"number"==typeof e.size&&"string"==typeof e.type&&"function"==typeof e.text&&"function"==typeof e.slice&&"function"==typeof e.arrayBuffer;async function t5(e,t,s){let n,r;if(tz(),null!=(n=e=await e)&&"object"==typeof n&&"string"==typeof n.name&&"number"==typeof n.lastModified&&t8(n))return e instanceof File?e:tG([await e.arrayBuffer()],e.name);if(null!=(r=e)&&"object"==typeof r&&"string"==typeof r.url&&"function"==typeof r.blob){let n=await e.blob();return t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()),tG(await t9(n),t,s)}let i=await t9(e);if(t||(t=tQ(e)),!s?.type){let e=i.find(e=>"object"==typeof e&&"type"in e&&e.type);"string"==typeof e&&(s={...s,type:e})}return tG(i,t,s)}async function t9(e){let t=[];if("string"==typeof e||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(t8(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if(tY(e))for await(let s of e)t.push(...await t9(s));else{let t=e?.constructor?.name;throw Error(`Unexpected data type: ${typeof e}${t?`; constructor: ${t}`:""}${function(e){if("object"!=typeof e||null===e)return"";let t=Object.getOwnPropertyNames(e);return`; props: [${t.map(e=>`"${e}"`).join(", ")}]`}(e)}`)}return t}class t7{constructor(e){this._client=e}}function se(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}let st=Object.freeze(Object.create(null)),ss=((e=se)=>function(t,...s){let n;if(1===t.length)return t[0];let r=!1,i=[],a=t.reduce((t,n,a)=>{/[?#]/.test(n)&&(r=!0);let o=s[a],l=(r?encodeURIComponent:e)(""+o);return a!==s.length&&(null==o||"object"==typeof o&&o.toString===Object.getPrototypeOf(Object.getPrototypeOf(o.hasOwnProperty??st)??st)?.toString)&&(l=o+"",i.push({start:t.length+n.length,length:l.length,error:`Value of type ${Object.prototype.toString.call(o).slice(8,-1)} is not a valid path parameter`})),t+n+(a===s.length?"":l)},""),o=a.split(/[?#]/,1)[0],l=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi;for(;null!==(n=l.exec(o));)i.push({start:n.index,length:n[0].length,error:`Value "${n[0]}" can't be safely passed as a path parameter`});if(i.sort((e,t)=>e.start-t.start),i.length>0){let e=0,t=i.reduce((t,s)=>{let n=" ".repeat(s.start-e),r="^".repeat(s.length);return e=s.start+s.length,t+n+r},"");throw new eG(`Path parameters result in path with invalid segments:
2
- ${i.map(e=>e.error).join("\n")}
3
- ${a}
4
- ${t}`)}return a})(se);class sn extends t7{list(e,t={},s){return this._client.getAPIList(ss`/chat/completions/${e}/messages`,tJ,{query:t,...s})}}function sr(e){return void 0!==e&&"function"in e&&void 0!==e.function}function si(e){return e?.$brand==="auto-parseable-response-format"}function sa(e){return e?.$brand==="auto-parseable-tool"}function so(e,t){let s=e.choices.map(e=>{var s,n;if("length"===e.finish_reason)throw new e7;if("content_filter"===e.finish_reason)throw new te;return sc(e.message.tool_calls),{...e,message:{...e.message,...e.message.tool_calls?{tool_calls:e.message.tool_calls?.map(e=>{var s,n;let r;return s=t,n=e,r=s.tools?.find(e=>sr(e)&&e.function?.name===n.function.name),{...n,function:{...n.function,parsed_arguments:sa(r)?r.$parseRaw(n.function.arguments):r?.function.strict?JSON.parse(n.function.arguments):null}}})??void 0}:void 0,parsed:e.message.content&&!e.message.refusal?(s=t,n=e.message.content,s.response_format?.type!=="json_schema"?null:s.response_format?.type==="json_schema"?"$parseRaw"in s.response_format?s.response_format.$parseRaw(n):JSON.parse(n):null):null}}});return{...e,choices:s}}function sl(e){return!!si(e.response_format)||(e.tools?.some(e=>sa(e)||"function"===e.type&&!0===e.function.strict)??!1)}function sc(e){for(let t of e||[])if("function"!==t.type)throw new eG(`Currently only \`function\` tool calls are supported; Received \`${t.type}\``)}let su=e=>e?.role==="assistant",sh=e=>e?.role==="tool";class sd{constructor(){u.add(this),this.controller=new AbortController,h.set(this,void 0),d.set(this,()=>{}),p.set(this,()=>{}),f.set(this,void 0),m.set(this,()=>{}),g.set(this,()=>{}),_.set(this,{}),w.set(this,!1),y.set(this,!1),b.set(this,!1),v.set(this,!1),eX(this,h,new Promise((e,t)=>{eX(this,d,e,"f"),eX(this,p,t,"f")}),"f"),eX(this,f,new Promise((e,t)=>{eX(this,m,e,"f"),eX(this,g,t,"f")}),"f"),eK(this,h,"f").catch(()=>{}),eK(this,f,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},eK(this,u,"m",x).bind(this))},0)}_connected(){this.ended||(eK(this,d,"f").call(this),this._emit("connect"))}get ended(){return eK(this,w,"f")}get errored(){return eK(this,y,"f")}get aborted(){return eK(this,b,"f")}abort(){this.controller.abort()}on(e,t){return(eK(this,_,"f")[e]||(eK(this,_,"f")[e]=[])).push({listener:t}),this}off(e,t){let s=eK(this,_,"f")[e];if(!s)return this;let n=s.findIndex(e=>e.listener===t);return n>=0&&s.splice(n,1),this}once(e,t){return(eK(this,_,"f")[e]||(eK(this,_,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,s)=>{eX(this,v,!0,"f"),"error"!==e&&this.once("error",s),this.once(e,t)})}async done(){eX(this,v,!0,"f"),await eK(this,f,"f")}_emit(e,...t){if(eK(this,w,"f"))return;"end"===e&&(eX(this,w,!0,"f"),eK(this,m,"f").call(this));let s=eK(this,_,"f")[e];if(s&&(eK(this,_,"f")[e]=s.filter(e=>!e.once),s.forEach(({listener:e})=>e(...t))),"abort"===e){let e=t[0];eK(this,v,"f")||s?.length||Promise.reject(e),eK(this,p,"f").call(this,e),eK(this,g,"f").call(this,e),this._emit("end");return}if("error"===e){let e=t[0];eK(this,v,"f")||s?.length||Promise.reject(e),eK(this,p,"f").call(this,e),eK(this,g,"f").call(this,e),this._emit("end")}}_emitFinal(){}}h=new WeakMap,d=new WeakMap,p=new WeakMap,f=new WeakMap,m=new WeakMap,g=new WeakMap,_=new WeakMap,w=new WeakMap,y=new WeakMap,b=new WeakMap,v=new WeakMap,u=new WeakSet,x=function(e){if(eX(this,y,!0,"f"),e instanceof Error&&"AbortError"===e.name&&(e=new eY),e instanceof eY)return eX(this,b,!0,"f"),this._emit("abort",e);if(e instanceof eG)return this._emit("error",e);if(e instanceof Error){let t=new eG(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new eG(String(e)))};class sp extends sd{constructor(){super(...arguments),S.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){this._chatCompletions.push(e),this._emit("chatCompletion",e);let t=e.choices[0]?.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),sh(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(su(e)&&e.tool_calls)for(let t of e.tool_calls)"function"===t.type&&this._emit("functionToolCall",t.function)}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new eG("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),eK(this,S,"m",$).call(this)}async finalMessage(){return await this.done(),eK(this,S,"m",A).call(this)}async finalFunctionToolCall(){return await this.done(),eK(this,S,"m",R).call(this)}async finalFunctionToolCallResult(){return await this.done(),eK(this,S,"m",I).call(this)}async totalUsage(){return await this.done(),eK(this,S,"m",O).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);let t=eK(this,S,"m",A).call(this);t&&this._emit("finalMessage",t);let s=eK(this,S,"m",$).call(this);s&&this._emit("finalContent",s);let n=eK(this,S,"m",R).call(this);n&&this._emit("finalFunctionToolCall",n);let r=eK(this,S,"m",I).call(this);null!=r&&this._emit("finalFunctionToolCallResult",r),this._chatCompletions.some(e=>e.usage)&&this._emit("totalUsage",eK(this,S,"m",O).call(this))}async _createChatCompletion(e,t,s){let n=s?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),eK(this,S,"m",E).call(this,t);let r=await e.chat.completions.create({...t,stream:!1},{...s,signal:this.controller.signal});return this._connected(),this._addChatCompletion(so(r,t))}async _runChatCompletion(e,t,s){for(let e of t.messages)this._addMessage(e,!1);return await this._createChatCompletion(e,t,s)}async _runTools(e,t,s){let n="tool",{tool_choice:r="auto",stream:i,...a}=t,o="string"!=typeof r&&"function"===r.type&&r?.function?.name,{maxChatCompletions:l=10}=s||{},c=t.tools.map(e=>{if(sa(e)){if(!e.$callback)throw new eG("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:e.$callback,name:e.function.name,description:e.function.description||"",parameters:e.function.parameters,parse:e.$parseRaw,strict:!0}}}return e}),u={};for(let e of c)"function"===e.type&&(u[e.function.name||e.function.function.name]=e.function);let h="tools"in t?c.map(e=>"function"===e.type?{type:"function",function:{name:e.function.name||e.function.function.name,parameters:e.function.parameters,description:e.function.description,strict:e.function.strict}}:e):void 0;for(let e of t.messages)this._addMessage(e,!1);for(let t=0;t<l;++t){let t=await this._createChatCompletion(e,{...a,tool_choice:r,tools:h,messages:[...this.messages]},s),i=t.choices[0]?.message;if(!i)throw new eG("missing message in ChatCompletion response");if(!i.tool_calls?.length)break;for(let e of i.tool_calls){let t;if("function"!==e.type)continue;let s=e.id,{name:r,arguments:i}=e.function,a=u[r];if(a){if(o&&o!==r){let e=`Invalid tool_call: ${JSON.stringify(r)}. ${JSON.stringify(o)} requested. Please try again`;this._addMessage({role:n,tool_call_id:s,content:e});continue}}else{let e=`Invalid tool_call: ${JSON.stringify(r)}. Available options are: ${Object.keys(u).map(e=>JSON.stringify(e)).join(", ")}. Please try again`;this._addMessage({role:n,tool_call_id:s,content:e});continue}try{t="function"==typeof a.parse?await a.parse(i):i}catch(t){let e=t instanceof Error?t.message:String(t);this._addMessage({role:n,tool_call_id:s,content:e});continue}let l=await a.function(t,this),c=eK(this,S,"m",k).call(this,l);if(this._addMessage({role:n,tool_call_id:s,content:c}),o)return}}}}S=new WeakSet,$=function(){return eK(this,S,"m",A).call(this).content??null},A=function(){let e=this.messages.length;for(;e-- >0;){let t=this.messages[e];if(su(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new eG("stream ended without producing a ChatCompletionMessage with role=assistant")},R=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(su(t)&&t?.tool_calls?.length)return t.tool_calls.filter(e=>"function"===e.type).at(-1)?.function}},I=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(sh(t)&&null!=t.content&&"string"==typeof t.content&&this.messages.some(e=>"assistant"===e.role&&e.tool_calls?.some(e=>"function"===e.type&&e.id===t.tool_call_id)))return t.content}},O=function(){let e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{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},E=function(e){if(null!=e.n&&e.n>1)throw new eG("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},k=function(e){return"string"==typeof e?e:void 0===e?"undefined":JSON.stringify(e)};class sf extends sp{static runTools(e,t,s){let n=new sf,r={...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"runTools"}};return n._run(()=>n._runTools(e,t,r)),n}_addMessage(e,t=!0){super._addMessage(e,t),su(e)&&e.content&&this._emit("content",e.content)}}let sm=511;class sg extends Error{}class s_ extends Error{}let sw=e=>(function(e,t=sm){var s,n;let r,i,a,o,l,c,u,h,d,p;if("string"!=typeof e)throw TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw Error(`${e} is empty`);return s=e.trim(),n=t,r=s.length,i=0,a=e=>{throw new sg(`${e} at position ${i}`)},o=e=>{throw new s_(`${e} at position ${i}`)},l=()=>(p(),i>=r&&a("Unexpected end of input"),'"'===s[i])?c():"{"===s[i]?u():"["===s[i]?h():"null"===s.substring(i,i+4)||16&n&&r-i<4&&"null".startsWith(s.substring(i))?(i+=4,null):"true"===s.substring(i,i+4)||32&n&&r-i<4&&"true".startsWith(s.substring(i))?(i+=4,!0):"false"===s.substring(i,i+5)||32&n&&r-i<5&&"false".startsWith(s.substring(i))?(i+=5,!1):"Infinity"===s.substring(i,i+8)||128&n&&r-i<8&&"Infinity".startsWith(s.substring(i))?(i+=8,1/0):"-Infinity"===s.substring(i,i+9)||256&n&&1<r-i&&r-i<9&&"-Infinity".startsWith(s.substring(i))?(i+=9,-1/0):"NaN"===s.substring(i,i+3)||64&n&&r-i<3&&"NaN".startsWith(s.substring(i))?(i+=3,NaN):d(),c=()=>{let e=i,t=!1;for(i++;i<r&&('"'!==s[i]||t&&"\\"===s[i-1]);)t="\\"===s[i]&&!t,i++;if('"'==s.charAt(i))try{return JSON.parse(s.substring(e,++i-Number(t)))}catch(e){o(String(e))}else if(1&n)try{return JSON.parse(s.substring(e,i-Number(t))+'"')}catch(t){return JSON.parse(s.substring(e,s.lastIndexOf("\\"))+'"')}a("Unterminated string literal")},u=()=>{i++,p();let e={};try{for(;"}"!==s[i];){if(p(),i>=r&&8&n)return e;let t=c();p(),i++;try{let s=l();Object.defineProperty(e,t,{value:s,writable:!0,enumerable:!0,configurable:!0})}catch(t){if(8&n)return e;throw t}p(),","===s[i]&&i++}}catch(t){if(8&n)return e;a("Expected '}' at end of object")}return i++,e},h=()=>{i++;let e=[];try{for(;"]"!==s[i];)e.push(l()),p(),","===s[i]&&i++}catch(t){if(4&n)return e;a("Expected ']' at end of array")}return i++,e},d=()=>{if(0===i){"-"===s&&2&n&&a("Not sure what '-' is");try{return JSON.parse(s)}catch(e){if(2&n)try{if("."===s[s.length-1])return JSON.parse(s.substring(0,s.lastIndexOf(".")));return JSON.parse(s.substring(0,s.lastIndexOf("e")))}catch(e){}o(String(e))}}let e=i;for("-"===s[i]&&i++;s[i]&&!",]}".includes(s[i]);)i++;i!=r||2&n||a("Unterminated number literal");try{return JSON.parse(s.substring(e,i))}catch(t){"-"===s.substring(e,i)&&2&n&&a("Not sure what '-' is");try{return JSON.parse(s.substring(e,s.lastIndexOf("e")))}catch(e){o(String(e))}}},p=()=>{for(;i<r&&" \n\r ".includes(s[i]);)i++},l()})(e,2^sm);class sy extends sp{constructor(e){super(),P.add(this),C.set(this,void 0),T.set(this,void 0),N.set(this,void 0),eX(this,C,e,"f"),eX(this,T,[],"f")}get currentChatCompletionSnapshot(){return eK(this,N,"f")}static fromReadableStream(e){let t=new sy(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,s){let n=new sy(t);return n._run(()=>n._runChatCompletion(e,{...t,stream:!0},{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),n}async _createChatCompletion(e,t,s){super._createChatCompletion;let n=s?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),eK(this,P,"m",j).call(this);let r=await e.chat.completions.create({...t,stream:!0},{...s,signal:this.controller.signal});for await(let e of(this._connected(),r))eK(this,P,"m",D).call(this,e);if(r.controller.signal?.aborted)throw new eY;return this._addChatCompletion(eK(this,P,"m",W).call(this))}async _fromReadableStream(e,t){let s,n=t?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),eK(this,P,"m",j).call(this),this._connected();let r=tD.fromReadableStream(e,this.controller);for await(let e of r)s&&s!==e.id&&this._addChatCompletion(eK(this,P,"m",W).call(this)),eK(this,P,"m",D).call(this,e),s=e.id;if(r.controller.signal?.aborted)throw new eY;return this._addChatCompletion(eK(this,P,"m",W).call(this))}[(C=new WeakMap,T=new WeakMap,N=new WeakMap,P=new WeakSet,j=function(){this.ended||eX(this,N,void 0,"f")},M=function(e){let t=eK(this,T,"f")[e.index];return t||(t={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},eK(this,T,"f")[e.index]=t),t},D=function(e){if(this.ended)return;let t=eK(this,P,"m",U).call(this,e);for(let s of(this._emit("chunk",e,t),e.choices)){let e=t.choices[s.index];null!=s.delta.content&&e.message?.role==="assistant"&&e.message?.content&&(this._emit("content",s.delta.content,e.message.content),this._emit("content.delta",{delta:s.delta.content,snapshot:e.message.content,parsed:e.message.parsed})),null!=s.delta.refusal&&e.message?.role==="assistant"&&e.message?.refusal&&this._emit("refusal.delta",{delta:s.delta.refusal,snapshot:e.message.refusal}),s.logprobs?.content!=null&&e.message?.role==="assistant"&&this._emit("logprobs.content.delta",{content:s.logprobs?.content,snapshot:e.logprobs?.content??[]}),s.logprobs?.refusal!=null&&e.message?.role==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:s.logprobs?.refusal,snapshot:e.logprobs?.refusal??[]});let n=eK(this,P,"m",M).call(this,e);for(let t of(e.finish_reason&&(eK(this,P,"m",B).call(this,e),null!=n.current_tool_call_index&&eK(this,P,"m",L).call(this,e,n.current_tool_call_index)),s.delta.tool_calls??[]))n.current_tool_call_index!==t.index&&(eK(this,P,"m",B).call(this,e),null!=n.current_tool_call_index&&eK(this,P,"m",L).call(this,e,n.current_tool_call_index)),n.current_tool_call_index=t.index;for(let t of s.delta.tool_calls??[]){let s=e.message.tool_calls?.[t.index];s?.type&&(s?.type==="function"?this._emit("tool_calls.function.arguments.delta",{name:s.function?.name,index:t.index,arguments:s.function.arguments,parsed_arguments:s.function.parsed_arguments,arguments_delta:t.function?.arguments??""}):sx(s?.type))}}},L=function(e,t){if(eK(this,P,"m",M).call(this,e).done_tool_calls.has(t))return;let s=e.message.tool_calls?.[t];if(!s)throw Error("no tool call snapshot");if(!s.type)throw Error("tool call snapshot missing `type`");if("function"===s.type){let e=eK(this,C,"f")?.tools?.find(e=>sr(e)&&e.function.name===s.function.name);this._emit("tool_calls.function.arguments.done",{name:s.function.name,index:t,arguments:s.function.arguments,parsed_arguments:sa(e)?e.$parseRaw(s.function.arguments):e?.function.strict?JSON.parse(s.function.arguments):null})}else sx(s.type)},B=function(e){let t=eK(this,P,"m",M).call(this,e);if(e.message.content&&!t.content_done){t.content_done=!0;let s=eK(this,P,"m",q).call(this);this._emit("content.done",{content:e.message.content,parsed:s?s.$parseRaw(e.message.content):null})}e.message.refusal&&!t.refusal_done&&(t.refusal_done=!0,this._emit("refusal.done",{refusal:e.message.refusal})),e.logprobs?.content&&!t.logprobs_content_done&&(t.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:e.logprobs.content})),e.logprobs?.refusal&&!t.logprobs_refusal_done&&(t.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:e.logprobs.refusal}))},W=function(){if(this.ended)throw new eG("stream has ended, this shouldn't happen");let e=eK(this,N,"f");if(!e)throw new eG("request ended without sending any chunks");return eX(this,N,void 0,"f"),eX(this,T,[],"f"),function(e,t){var s;let{id:n,choices:r,created:i,model:a,system_fingerprint:o,...l}=e;return s={...l,id:n,choices:r.map(({message:t,finish_reason:s,index:n,logprobs:r,...i})=>{if(!s)throw new eG(`missing finish_reason for choice ${n}`);let{content:a=null,function_call:o,tool_calls:l,...c}=t,u=t.role;if(!u)throw new eG(`missing role for choice ${n}`);if(o){let{arguments:e,name:l}=o;if(null==e)throw new eG(`missing function_call.arguments for choice ${n}`);if(!l)throw new eG(`missing function_call.name for choice ${n}`);return{...i,message:{content:a,function_call:{arguments:e,name:l},role:u,refusal:t.refusal??null},finish_reason:s,index:n,logprobs:r}}return l?{...i,index:n,finish_reason:s,logprobs:r,message:{...c,role:u,content:a,refusal:t.refusal??null,tool_calls:l.map((t,s)=>{let{function:r,type:i,id:a,...o}=t,{arguments:l,name:c,...u}=r||{};if(null==a)throw new eG(`missing choices[${n}].tool_calls[${s}].id
5
- ${sb(e)}`);if(null==i)throw new eG(`missing choices[${n}].tool_calls[${s}].type
6
- ${sb(e)}`);if(null==c)throw new eG(`missing choices[${n}].tool_calls[${s}].function.name
7
- ${sb(e)}`);if(null==l)throw new eG(`missing choices[${n}].tool_calls[${s}].function.arguments
8
- ${sb(e)}`);return{...o,id:a,type:i,function:{...u,name:c,arguments:l}}})}}:{...i,message:{...c,content:a,role:u,refusal:t.refusal??null},finish_reason:s,index:n,logprobs:r}}),created:i,model:a,object:"chat.completion",...o?{system_fingerprint:o}:{}},t&&sl(t)?so(s,t):{...s,choices:s.choices.map(e=>(sc(e.message.tool_calls),{...e,message:{...e.message,parsed:null,...e.message.tool_calls?{tool_calls:e.message.tool_calls}:void 0}}))}}(e,eK(this,C,"f"))},q=function(){let e=eK(this,C,"f")?.response_format;return si(e)?e:null},U=function(e){var t,s,n,r;let i=eK(this,N,"f"),{choices:a,...o}=e;for(let{delta:a,finish_reason:l,index:c,logprobs:u=null,...h}of(i?Object.assign(i,o):i=eX(this,N,{...o,choices:[]},"f"),e.choices)){let e=i.choices[c];if(e||(e=i.choices[c]={finish_reason:l,index:c,message:{},logprobs:u,...h}),u)if(e.logprobs){let{content:n,refusal:r,...i}=u;sv(i),Object.assign(e.logprobs,i),n&&((t=e.logprobs).content??(t.content=[]),e.logprobs.content.push(...n)),r&&((s=e.logprobs).refusal??(s.refusal=[]),e.logprobs.refusal.push(...r))}else e.logprobs=Object.assign({},u);if(l&&(e.finish_reason=l,eK(this,C,"f")&&sl(eK(this,C,"f")))){if("length"===l)throw new e7;if("content_filter"===l)throw new te}if(Object.assign(e,h),!a)continue;let{content:o,refusal:d,function_call:p,role:f,tool_calls:m,...g}=a;if(sv(g),Object.assign(e.message,g),d&&(e.message.refusal=(e.message.refusal||"")+d),f&&(e.message.role=f),p&&(e.message.function_call?(p.name&&(e.message.function_call.name=p.name),p.arguments&&((n=e.message.function_call).arguments??(n.arguments=""),e.message.function_call.arguments+=p.arguments)):e.message.function_call=p),o&&(e.message.content=(e.message.content||"")+o,!e.message.refusal&&eK(this,P,"m",q).call(this)&&(e.message.parsed=sw(e.message.content))),m)for(let{index:t,id:s,type:n,function:i,...a}of(e.message.tool_calls||(e.message.tool_calls=[]),m)){let o=(r=e.message.tool_calls)[t]??(r[t]={});Object.assign(o,a),s&&(o.id=s),n&&(o.type=n),i&&(o.function??(o.function={name:i.name??"",arguments:""})),i?.name&&(o.function.name=i.name),i?.arguments&&(o.function.arguments+=i.arguments,function(e,t){if(!e||!("tools"in e)||!e.tools)return!1;let s=e.tools?.find(e=>sr(e)&&e.function?.name===t.function.name);return sr(s)&&(sa(s)||s?.function.strict||!1)}(eK(this,C,"f"),o)&&(o.function.parsed_arguments=sw(o.function.arguments)))}}return i},Symbol.asyncIterator)](){let e=[],t=[],s=!1;return this.on("chunk",s=>{let n=t.shift();n?n.resolve(s):e.push(s)}),this.on("end",()=>{for(let e of(s=!0,t))e.resolve(void 0);t.length=0}),this.on("abort",e=>{for(let n of(s=!0,t))n.reject(e);t.length=0}),this.on("error",e=>{for(let n of(s=!0,t))n.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:s?{value:void 0,done:!0}:new Promise((e,s)=>t.push({resolve:e,reject:s})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new tD(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function sb(e){return JSON.stringify(e)}function sv(e){}function sx(e){}class sS extends sy{static fromReadableStream(e){let t=new sS(null);return t._run(()=>t._fromReadableStream(e)),t}static runTools(e,t,s){let n=new sS(t),r={...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"runTools"}};return n._run(()=>n._runTools(e,t,r)),n}}class s$ extends t7{constructor(){super(...arguments),this.messages=new sn(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(ss`/chat/completions/${e}`,t)}update(e,t,s){return this._client.post(ss`/chat/completions/${e}`,{body:t,...s})}list(e={},t){return this._client.getAPIList("/chat/completions",tJ,{query:e,...t})}delete(e,t){return this._client.delete(ss`/chat/completions/${e}`,t)}parse(e,t){for(let t of e.tools??[]){if("function"!==t.type)throw new eG(`Currently only \`function\` tool types support auto-parsing; Received \`${t.type}\``);if(!0!==t.function.strict)throw new eG(`The \`${t.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}return this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(t=>so(t,e))}runTools(e,t){return e.stream?sS.runTools(this._client,e,t):sf.runTools(this._client,e,t)}stream(e,t){return sy.createChatCompletion(this._client,e,t)}}s$.Messages=sn;class sA extends t7{constructor(){super(...arguments),this.completions=new s$(this._client)}}sA.Completions=s$,e.s([],98546);let sR=Symbol("brand.privateNullableHeaders"),sI=e=>{let t=new Headers,s=new Set;for(let n of e){let e=new Set;for(let[r,i]of function*(e){let t;if(!e)return;if(sR in e){let{values:t,nulls:s}=e;for(let e of(yield*t.entries(),s))yield[e,null];return}let s=!1;for(let n of(e instanceof Headers?t=e.entries():tr(e)?t=e:(s=!0,t=Object.entries(e??{})),t)){let e=n[0];if("string"!=typeof e)throw TypeError("expected header name to be a string");let t=tr(n[1])?n[1]:[n[1]],r=!1;for(let n of t)void 0!==n&&(s&&!r&&(r=!0,yield[e,null]),yield[e,n])}}(n)){let n=r.toLowerCase();e.has(n)||(t.delete(r),e.add(n)),null===i?(t.delete(r),s.add(n)):(t.append(r,i),s.delete(n))}}return{[sR]:!0,values:t,nulls:s}};class sO extends t7{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:sI([{Accept:"application/octet-stream"},t?.headers]),__binaryResponse:!0})}}class sE extends t7{create(e,t){return this._client.post("/audio/transcriptions",t0({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}}class sk extends t7{create(e,t){return this._client.post("/audio/translations",t0({body:e,...t,__metadata:{model:e.model}},this._client))}}class sP extends t7{constructor(){super(...arguments),this.transcriptions=new sE(this._client),this.translations=new sk(this._client),this.speech=new sO(this._client)}}sP.Transcriptions=sE,sP.Translations=sk,sP.Speech=sO;class sC extends t7{create(e,t){return this._client.post("/batches",{body:e,...t})}retrieve(e,t){return this._client.get(ss`/batches/${e}`,t)}list(e={},t){return this._client.getAPIList("/batches",tJ,{query:e,...t})}cancel(e,t){return this._client.post(ss`/batches/${e}/cancel`,t)}}class sT extends t7{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:sI([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(ss`/assistants/${e}`,{...t,headers:sI([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,s){return this._client.post(ss`/assistants/${e}`,{body:t,...s,headers:sI([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e={},t){return this._client.getAPIList("/assistants",tJ,{query:e,...t,headers:sI([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(ss`/assistants/${e}`,{...t,headers:sI([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}class sN extends t7{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:sI([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}class sj extends t7{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:sI([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}class sM extends t7{constructor(){super(...arguments),this.sessions=new sN(this._client),this.transcriptionSessions=new sj(this._client)}}sM.Sessions=sN,sM.TranscriptionSessions=sj;class sD extends t7{create(e,t){return this._client.post("/chatkit/sessions",{body:e,...t,headers:sI([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}cancel(e,t){return this._client.post(ss`/chatkit/sessions/${e}/cancel`,{...t,headers:sI([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}}class sL extends t7{retrieve(e,t){return this._client.get(ss`/chatkit/threads/${e}`,{...t,headers:sI([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}list(e={},t){return this._client.getAPIList("/chatkit/threads",tV,{query:e,...t,headers:sI([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}delete(e,t){return this._client.delete(ss`/chatkit/threads/${e}`,{...t,headers:sI([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}listItems(e,t={},s){return this._client.getAPIList(ss`/chatkit/threads/${e}/items`,tV,{query:t,...s,headers:sI([{"OpenAI-Beta":"chatkit_beta=v1"},s?.headers])})}}class sB extends t7{constructor(){super(...arguments),this.sessions=new sD(this._client),this.threads=new sL(this._client)}}sB.Sessions=sD,sB.Threads=sL;class sW extends t7{create(e,t,s){return this._client.post(ss`/threads/${e}/messages`,{body:t,...s,headers:sI([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}retrieve(e,t,s){let{thread_id:n}=t;return this._client.get(ss`/threads/${n}/messages/${e}`,{...s,headers:sI([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}update(e,t,s){let{thread_id:n,...r}=t;return this._client.post(ss`/threads/${n}/messages/${e}`,{body:r,...s,headers:sI([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e,t={},s){return this._client.getAPIList(ss`/threads/${e}/messages`,tJ,{query:t,...s,headers:sI([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}delete(e,t,s){let{thread_id:n}=t;return this._client.delete(ss`/threads/${n}/messages/${e}`,{...s,headers:sI([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}}class sq extends t7{retrieve(e,t,s){let{thread_id:n,run_id:r,...i}=t;return this._client.get(ss`/threads/${n}/runs/${r}/steps/${e}`,{query:i,...s,headers:sI([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e,t,s){let{thread_id:n,...r}=t;return this._client.getAPIList(ss`/threads/${n}/runs/${e}/steps`,tJ,{query:r,...s,headers:sI([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}}let sU=e=>void 0!==globalThis.process?globalThis.process.env?.[e]?.trim()??void 0:void 0!==globalThis.Deno?globalThis.Deno.env?.get?.(e)?.trim():void 0;class sH extends sd{constructor(){super(...arguments),H.add(this),X.set(this,[]),K.set(this,{}),J.set(this,{}),V.set(this,void 0),z.set(this,void 0),G.set(this,void 0),Q.set(this,void 0),Y.set(this,void 0),Z.set(this,void 0),ee.set(this,void 0),et.set(this,void 0),es.set(this,void 0)}[(X=new WeakMap,K=new WeakMap,J=new WeakMap,V=new WeakMap,z=new WeakMap,G=new WeakMap,Q=new WeakMap,Y=new WeakMap,Z=new WeakMap,ee=new WeakMap,et=new WeakMap,es=new WeakMap,H=new WeakSet,Symbol.asyncIterator)](){let e=[],t=[],s=!1;return this.on("event",s=>{let n=t.shift();n?n.resolve(s):e.push(s)}),this.on("end",()=>{for(let e of(s=!0,t))e.resolve(void 0);t.length=0}),this.on("abort",e=>{for(let n of(s=!0,t))n.reject(e);t.length=0}),this.on("error",e=>{for(let n of(s=!0,t))n.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:s?{value:void 0,done:!0}:new Promise((e,s)=>t.push({resolve:e,reject:s})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){let t=new F;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){let s=t?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),this._connected();let n=tD.fromReadableStream(e,this.controller);for await(let e of n)eK(this,H,"m",en).call(this,e);if(n.controller.signal?.aborted)throw new eY;return this._addRun(eK(this,H,"m",er).call(this))}toReadableStream(){return new tD(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,s,n){let r=new F;return r._run(()=>r._runToolAssistantStream(e,t,s,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),r}async _createToolAssistantStream(e,t,s,n){let r=n?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort()));let i={...s,stream:!0},a=await e.submitToolOutputs(t,i,{...n,signal:this.controller.signal});for await(let e of(this._connected(),a))eK(this,H,"m",en).call(this,e);if(a.controller.signal?.aborted)throw new eY;return this._addRun(eK(this,H,"m",er).call(this))}static createThreadAssistantStream(e,t,s){let n=new F;return n._run(()=>n._threadAssistantStream(e,t,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),n}static createAssistantStream(e,t,s,n){let r=new F;return r._run(()=>r._runAssistantStream(e,t,s,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),r}currentEvent(){return eK(this,ee,"f")}currentRun(){return eK(this,et,"f")}currentMessageSnapshot(){return eK(this,V,"f")}currentRunStepSnapshot(){return eK(this,es,"f")}async finalRunSteps(){return await this.done(),Object.values(eK(this,K,"f"))}async finalMessages(){return await this.done(),Object.values(eK(this,J,"f"))}async finalRun(){if(await this.done(),!eK(this,z,"f"))throw Error("Final run was not received.");return eK(this,z,"f")}async _createThreadAssistantStream(e,t,s){let n=s?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort()));let r={...t,stream:!0},i=await e.createAndRun(r,{...s,signal:this.controller.signal});for await(let e of(this._connected(),i))eK(this,H,"m",en).call(this,e);if(i.controller.signal?.aborted)throw new eY;return this._addRun(eK(this,H,"m",er).call(this))}async _createAssistantStream(e,t,s,n){let r=n?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort()));let i={...s,stream:!0},a=await e.create(t,i,{...n,signal:this.controller.signal});for await(let e of(this._connected(),a))eK(this,H,"m",en).call(this,e);if(a.controller.signal?.aborted)throw new eY;return this._addRun(eK(this,H,"m",er).call(this))}static accumulateDelta(e,t){for(let[s,n]of Object.entries(t)){if(!e.hasOwnProperty(s)){e[s]=n;continue}let t=e[s];if(null==t||"index"===s||"type"===s){e[s]=n;continue}if("string"==typeof t&&"string"==typeof n)t+=n;else if("number"==typeof t&&"number"==typeof n)t+=n;else if(ta(t)&&ta(n))t=this.accumulateDelta(t,n);else if(Array.isArray(t)&&Array.isArray(n)){if(t.every(e=>"string"==typeof e||"number"==typeof e)){t.push(...n);continue}for(let e of n){if(!ta(e))throw Error(`Expected array delta entry to be an object but got: ${e}`);let s=e.index;if(null==s)throw console.error(e),Error("Expected array delta entry to have an `index` property");if("number"!=typeof s)throw Error(`Expected array delta entry \`index\` property to be a number but got ${s}`);let n=t[s];null==n?t.push(e):t[s]=this.accumulateDelta(n,e)}continue}else throw Error(`Unhandled record type: ${s}, deltaValue: ${n}, accValue: ${t}`);e[s]=t}return e}_addRun(e){return e}async _threadAssistantStream(e,t,s){return await this._createThreadAssistantStream(t,e,s)}async _runAssistantStream(e,t,s,n){return await this._createAssistantStream(t,e,s,n)}async _runToolAssistantStream(e,t,s,n){return await this._createToolAssistantStream(t,e,s,n)}}F=sH,en=function(e){if(!this.ended)switch(eX(this,ee,e,"f"),eK(this,H,"m",eo).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":eK(this,H,"m",eh).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":eK(this,H,"m",ea).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":eK(this,H,"m",ei).call(this,e);break;case"error":throw Error("Encountered an error event in event processing - errors should be processed earlier")}},er=function(){if(this.ended)throw new eG("stream has ended, this shouldn't happen");if(!eK(this,z,"f"))throw Error("Final run has not been received");return eK(this,z,"f")},ei=function(e){let[t,s]=eK(this,H,"m",ec).call(this,e,eK(this,V,"f"));for(let e of(eX(this,V,t,"f"),eK(this,J,"f")[t.id]=t,s)){let s=t.content[e.index];s?.type=="text"&&this._emit("textCreated",s.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(let s of e.data.delta.content){if("text"==s.type&&s.text){let e=s.text,n=t.content[s.index];if(n&&"text"==n.type)this._emit("textDelta",e,n.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(s.index!=eK(this,G,"f")){if(eK(this,Q,"f"))switch(eK(this,Q,"f").type){case"text":this._emit("textDone",eK(this,Q,"f").text,eK(this,V,"f"));break;case"image_file":this._emit("imageFileDone",eK(this,Q,"f").image_file,eK(this,V,"f"))}eX(this,G,s.index,"f")}eX(this,Q,t.content[s.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(void 0!==eK(this,G,"f")){let t=e.data.content[eK(this,G,"f")];if(t)switch(t.type){case"image_file":this._emit("imageFileDone",t.image_file,eK(this,V,"f"));break;case"text":this._emit("textDone",t.text,eK(this,V,"f"))}}eK(this,V,"f")&&this._emit("messageDone",e.data),eX(this,V,void 0,"f")}},ea=function(e){let t=eK(this,H,"m",el).call(this,e);switch(eX(this,es,t,"f"),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":let s=e.data.delta;if(s.step_details&&"tool_calls"==s.step_details.type&&s.step_details.tool_calls&&"tool_calls"==t.step_details.type)for(let e of s.step_details.tool_calls)e.index==eK(this,Y,"f")?this._emit("toolCallDelta",e,t.step_details.tool_calls[e.index]):(eK(this,Z,"f")&&this._emit("toolCallDone",eK(this,Z,"f")),eX(this,Y,e.index,"f"),eX(this,Z,t.step_details.tool_calls[e.index],"f"),eK(this,Z,"f")&&this._emit("toolCallCreated",eK(this,Z,"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":eX(this,es,void 0,"f"),"tool_calls"==e.data.step_details.type&&eK(this,Z,"f")&&(this._emit("toolCallDone",eK(this,Z,"f")),eX(this,Z,void 0,"f")),this._emit("runStepDone",e.data,t)}},eo=function(e){eK(this,X,"f").push(e),this._emit("event",e)},el=function(e){switch(e.event){case"thread.run.step.created":return eK(this,K,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=eK(this,K,"f")[e.data.id];if(!t)throw Error("Received a RunStepDelta before creation of a snapshot");let s=e.data;if(s.delta){let n=F.accumulateDelta(t,s.delta);eK(this,K,"f")[e.data.id]=n}return eK(this,K,"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":eK(this,K,"f")[e.data.id]=e.data}if(eK(this,K,"f")[e.data.id])return eK(this,K,"f")[e.data.id];throw Error("No snapshot available")},ec=function(e,t){let s=[];switch(e.event){case"thread.message.created":return[e.data,s];case"thread.message.delta":if(!t)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let n=e.data;if(n.delta.content)for(let e of n.delta.content)if(e.index in t.content){let s=t.content[e.index];t.content[e.index]=eK(this,H,"m",eu).call(this,e,s)}else t.content[e.index]=e,s.push(e);return[t,s];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(t)return[t,s];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},eu=function(e,t){return F.accumulateDelta(t,e)},eh=function(e){switch(eX(this,et,e.data,"f"),e.event){case"thread.run.created":case"thread.run.queued":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":eX(this,z,e.data,"f"),eK(this,Z,"f")&&(this._emit("toolCallDone",eK(this,Z,"f")),eX(this,Z,void 0,"f"))}};class sF extends t7{constructor(){super(...arguments),this.steps=new sq(this._client)}create(e,t,s){let{include:n,...r}=t;return this._client.post(ss`/threads/${e}/runs`,{query:{include:n},body:r,...s,headers:sI([{"OpenAI-Beta":"assistants=v2"},s?.headers]),stream:t.stream??!1})}retrieve(e,t,s){let{thread_id:n}=t;return this._client.get(ss`/threads/${n}/runs/${e}`,{...s,headers:sI([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}update(e,t,s){let{thread_id:n,...r}=t;return this._client.post(ss`/threads/${n}/runs/${e}`,{body:r,...s,headers:sI([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e,t={},s){return this._client.getAPIList(ss`/threads/${e}/runs`,tJ,{query:t,...s,headers:sI([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}cancel(e,t,s){let{thread_id:n}=t;return this._client.post(ss`/threads/${n}/runs/${e}/cancel`,{...s,headers:sI([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}async createAndPoll(e,t,s){let n=await this.create(e,t,s);return await this.poll(n.id,{thread_id:e},s)}createAndStream(e,t,s){return sH.createAssistantStream(e,this._client.beta.threads.runs,t,s)}async poll(e,t,s){let n=sI([s?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":s?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:r,response:i}=await this.retrieve(e,t,{...s,headers:{...s?.headers,...n}}).withResponse();switch(r.status){case"queued":case"in_progress":case"cancelling":let a=5e3;if(s?.pollIntervalMs)a=s.pollIntervalMs;else{let e=i.headers.get("openai-poll-after-ms");if(e){let t=parseInt(e);isNaN(t)||(a=t)}}await to(a);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return r}}}stream(e,t,s){return sH.createAssistantStream(e,this._client.beta.threads.runs,t,s)}submitToolOutputs(e,t,s){let{thread_id:n,...r}=t;return this._client.post(ss`/threads/${n}/runs/${e}/submit_tool_outputs`,{body:r,...s,headers:sI([{"OpenAI-Beta":"assistants=v2"},s?.headers]),stream:t.stream??!1})}async submitToolOutputsAndPoll(e,t,s){let n=await this.submitToolOutputs(e,t,s);return await this.poll(n.id,t,s)}submitToolOutputsStream(e,t,s){return sH.createToolAssistantStream(e,this._client.beta.threads.runs,t,s)}}sF.Steps=sq;class sX extends t7{constructor(){super(...arguments),this.runs=new sF(this._client),this.messages=new sW(this._client)}create(e={},t){return this._client.post("/threads",{body:e,...t,headers:sI([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(ss`/threads/${e}`,{...t,headers:sI([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,s){return this._client.post(ss`/threads/${e}`,{body:t,...s,headers:sI([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}delete(e,t){return this._client.delete(ss`/threads/${e}`,{...t,headers:sI([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:sI([{"OpenAI-Beta":"assistants=v2"},t?.headers]),stream:e.stream??!1})}async createAndRunPoll(e,t){let s=await this.createAndRun(e,t);return await this.runs.poll(s.id,{thread_id:s.thread_id},t)}createAndRunStream(e,t){return sH.createThreadAssistantStream(e,this._client.beta.threads,t)}}sX.Runs=sF,sX.Messages=sW;class sK extends t7{constructor(){super(...arguments),this.realtime=new sM(this._client),this.chatkit=new sB(this._client),this.assistants=new sT(this._client),this.threads=new sX(this._client)}}sK.Realtime=sM,sK.ChatKit=sB,sK.Assistants=sT,sK.Threads=sX;class sJ extends t7{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}}class sV extends t7{retrieve(e,t,s){let{container_id:n}=t;return this._client.get(ss`/containers/${n}/files/${e}/content`,{...s,headers:sI([{Accept:"application/binary"},s?.headers]),__binaryResponse:!0})}}class sz extends t7{constructor(){super(...arguments),this.content=new sV(this._client)}create(e,t,s){return this._client.post(ss`/containers/${e}/files`,tZ({body:t,...s},this._client))}retrieve(e,t,s){let{container_id:n}=t;return this._client.get(ss`/containers/${n}/files/${e}`,s)}list(e,t={},s){return this._client.getAPIList(ss`/containers/${e}/files`,tJ,{query:t,...s})}delete(e,t,s){let{container_id:n}=t;return this._client.delete(ss`/containers/${n}/files/${e}`,{...s,headers:sI([{Accept:"*/*"},s?.headers])})}}sz.Content=sV;class sG extends t7{constructor(){super(...arguments),this.files=new sz(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t})}retrieve(e,t){return this._client.get(ss`/containers/${e}`,t)}list(e={},t){return this._client.getAPIList("/containers",tJ,{query:e,...t})}delete(e,t){return this._client.delete(ss`/containers/${e}`,{...t,headers:sI([{Accept:"*/*"},t?.headers])})}}sG.Files=sz;class sQ extends t7{create(e,t,s){let{include:n,...r}=t;return this._client.post(ss`/conversations/${e}/items`,{query:{include:n},body:r,...s})}retrieve(e,t,s){let{conversation_id:n,...r}=t;return this._client.get(ss`/conversations/${n}/items/${e}`,{query:r,...s})}list(e,t={},s){return this._client.getAPIList(ss`/conversations/${e}/items`,tV,{query:t,...s})}delete(e,t,s){let{conversation_id:n}=t;return this._client.delete(ss`/conversations/${n}/items/${e}`,s)}}class sY extends t7{constructor(){super(...arguments),this.items=new sQ(this._client)}create(e={},t){return this._client.post("/conversations",{body:e,...t})}retrieve(e,t){return this._client.get(ss`/conversations/${e}`,t)}update(e,t,s){return this._client.post(ss`/conversations/${e}`,{body:t,...s})}delete(e,t){return this._client.delete(ss`/conversations/${e}`,t)}}sY.Items=sQ;class sZ extends t7{create(e,t){let s=!!e.encoding_format,n=s?e.encoding_format:"base64";s&&tj(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);let r=this._client.post("/embeddings",{body:{...e,encoding_format:n},...t});return s?r:(tj(this._client).debug("embeddings/decoding base64 embeddings from base64"),r._thenUnwrap(e=>(e&&e.data&&e.data.forEach(e=>{let t=e.embedding;e.embedding=(e=>{if("u">typeof Buffer){let t=Buffer.from(e,"base64");return Array.from(new Float32Array(t.buffer,t.byteOffset,t.length/Float32Array.BYTES_PER_ELEMENT))}{let t=atob(e),s=t.length,n=new Uint8Array(s);for(let e=0;e<s;e++)n[e]=t.charCodeAt(e);return Array.from(new Float32Array(n.buffer))}})(t)}),e)))}}class s0 extends t7{retrieve(e,t,s){let{eval_id:n,run_id:r}=t;return this._client.get(ss`/evals/${n}/runs/${r}/output_items/${e}`,s)}list(e,t,s){let{eval_id:n,...r}=t;return this._client.getAPIList(ss`/evals/${n}/runs/${e}/output_items`,tJ,{query:r,...s})}}class s1 extends t7{constructor(){super(...arguments),this.outputItems=new s0(this._client)}create(e,t,s){return this._client.post(ss`/evals/${e}/runs`,{body:t,...s})}retrieve(e,t,s){let{eval_id:n}=t;return this._client.get(ss`/evals/${n}/runs/${e}`,s)}list(e,t={},s){return this._client.getAPIList(ss`/evals/${e}/runs`,tJ,{query:t,...s})}delete(e,t,s){let{eval_id:n}=t;return this._client.delete(ss`/evals/${n}/runs/${e}`,s)}cancel(e,t,s){let{eval_id:n}=t;return this._client.post(ss`/evals/${n}/runs/${e}`,s)}}s1.OutputItems=s0;class s2 extends t7{constructor(){super(...arguments),this.runs=new s1(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t})}retrieve(e,t){return this._client.get(ss`/evals/${e}`,t)}update(e,t,s){return this._client.post(ss`/evals/${e}`,{body:t,...s})}list(e={},t){return this._client.getAPIList("/evals",tJ,{query:e,...t})}delete(e,t){return this._client.delete(ss`/evals/${e}`,t)}}s2.Runs=s1;class s4 extends t7{create(e,t){return this._client.post("/files",t0({body:e,...t},this._client))}retrieve(e,t){return this._client.get(ss`/files/${e}`,t)}list(e={},t){return this._client.getAPIList("/files",tJ,{query:e,...t})}delete(e,t){return this._client.delete(ss`/files/${e}`,t)}content(e,t){return this._client.get(ss`/files/${e}/content`,{...t,headers:sI([{Accept:"application/binary"},t?.headers]),__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:s=18e5}={}){let n=new Set(["processed","error","deleted"]),r=Date.now(),i=await this.retrieve(e);for(;!i.status||!n.has(i.status);)if(await to(t),i=await this.retrieve(e),Date.now()-r>s)throw new e0({message:`Giving up on waiting for file ${e} to finish processing after ${s} milliseconds.`});return i}}class s6 extends t7{}class s3 extends t7{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 s8 extends t7{constructor(){super(...arguments),this.graders=new s3(this._client)}}s8.Graders=s3;class s5 extends t7{create(e,t,s){return this._client.getAPIList(ss`/fine_tuning/checkpoints/${e}/permissions`,tK,{body:t,method:"post",...s})}retrieve(e,t={},s){return this._client.get(ss`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...s})}delete(e,t,s){let{fine_tuned_model_checkpoint:n}=t;return this._client.delete(ss`/fine_tuning/checkpoints/${n}/permissions/${e}`,s)}}class s9 extends t7{constructor(){super(...arguments),this.permissions=new s5(this._client)}}s9.Permissions=s5;class s7 extends t7{list(e,t={},s){return this._client.getAPIList(ss`/fine_tuning/jobs/${e}/checkpoints`,tJ,{query:t,...s})}}class ne extends t7{constructor(){super(...arguments),this.checkpoints=new s7(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this._client.get(ss`/fine_tuning/jobs/${e}`,t)}list(e={},t){return this._client.getAPIList("/fine_tuning/jobs",tJ,{query:e,...t})}cancel(e,t){return this._client.post(ss`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},s){return this._client.getAPIList(ss`/fine_tuning/jobs/${e}/events`,tJ,{query:t,...s})}pause(e,t){return this._client.post(ss`/fine_tuning/jobs/${e}/pause`,t)}resume(e,t){return this._client.post(ss`/fine_tuning/jobs/${e}/resume`,t)}}ne.Checkpoints=s7;class nt extends t7{constructor(){super(...arguments),this.methods=new s6(this._client),this.jobs=new ne(this._client),this.checkpoints=new s9(this._client),this.alpha=new s8(this._client)}}nt.Methods=s6,nt.Jobs=ne,nt.Checkpoints=s9,nt.Alpha=s8;class ns extends t7{}class nn extends t7{constructor(){super(...arguments),this.graderModels=new ns(this._client)}}nn.GraderModels=ns;class nr extends t7{createVariation(e,t){return this._client.post("/images/variations",t0({body:e,...t},this._client))}edit(e,t){return this._client.post("/images/edits",t0({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 ni extends t7{retrieve(e,t){return this._client.get(ss`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",tK,e)}delete(e,t){return this._client.delete(ss`/models/${e}`,t)}}class na extends t7{create(e,t){return this._client.post("/moderations",{body:e,...t})}}class no extends t7{accept(e,t,s){return this._client.post(ss`/realtime/calls/${e}/accept`,{body:t,...s,headers:sI([{Accept:"*/*"},s?.headers])})}hangup(e,t){return this._client.post(ss`/realtime/calls/${e}/hangup`,{...t,headers:sI([{Accept:"*/*"},t?.headers])})}refer(e,t,s){return this._client.post(ss`/realtime/calls/${e}/refer`,{body:t,...s,headers:sI([{Accept:"*/*"},s?.headers])})}reject(e,t={},s){return this._client.post(ss`/realtime/calls/${e}/reject`,{body:t,...s,headers:sI([{Accept:"*/*"},s?.headers])})}}class nl extends t7{create(e,t){return this._client.post("/realtime/client_secrets",{body:e,...t})}}class nc extends t7{constructor(){super(...arguments),this.clientSecrets=new nl(this._client),this.calls=new no(this._client)}}function nu(e,t){let s=e.output.map(e=>{if("function_call"===e.type)return{...e,parsed_arguments:function(e,t){var s,n;let r=(s=e.tools??[],n=t.name,s.find(e=>"function"===e.type&&e.name===n));return{...t,...t,parsed_arguments:r?.$brand==="auto-parseable-tool"?r.$parseRaw(t.arguments):r?.strict?JSON.parse(t.arguments):null}}(t,e)};if("message"===e.type){let s=e.content.map(e=>{var s,n;return"output_text"===e.type?{...e,parsed:(s=t,n=e.text,s.text?.format?.type!=="json_schema"?null:"$parseRaw"in s.text?.format?(s.text?.format).$parseRaw(n):JSON.parse(n))}:e});return{...e,content:s}}return e}),n=Object.assign({},e,{output:s});return Object.getOwnPropertyDescriptor(e,"output_text")||nh(n),Object.defineProperty(n,"output_parsed",{enumerable:!0,get(){for(let e of n.output)if("message"===e.type){for(let t of e.content)if("output_text"===t.type&&null!==t.parsed)return t.parsed}return null}}),n}function nh(e){let t=[];for(let s of e.output)if("message"===s.type)for(let e of s.content)"output_text"===e.type&&t.push(e.text);e.output_text=t.join("")}nc.ClientSecrets=nl,nc.Calls=no;class nd extends sd{constructor(e){super(),ed.add(this),ep.set(this,void 0),ef.set(this,void 0),em.set(this,void 0),eX(this,ep,e,"f")}static createResponse(e,t,s){let n=new nd(t);return n._run(()=>n._createOrRetrieveResponse(e,t,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),n}async _createOrRetrieveResponse(e,t,s){let n,r=s?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),eK(this,ed,"m",eg).call(this);let i=null;for await(let r of("response_id"in t?(n=await e.responses.retrieve(t.response_id,{stream:!0},{...s,signal:this.controller.signal,stream:!0}),i=t.starting_after??null):n=await e.responses.create({...t,stream:!0},{...s,signal:this.controller.signal}),this._connected(),n))eK(this,ed,"m",e_).call(this,r,i);if(n.controller.signal?.aborted)throw new eY;return eK(this,ed,"m",ew).call(this)}[(ep=new WeakMap,ef=new WeakMap,em=new WeakMap,ed=new WeakSet,eg=function(){this.ended||eX(this,ef,void 0,"f")},e_=function(e,t){if(this.ended)return;let s=(e,s)=>{(null==t||s.sequence_number>t)&&this._emit(e,s)},n=eK(this,ed,"m",ey).call(this,e);switch(s("event",e),e.type){case"response.output_text.delta":{let t=n.output[e.output_index];if(!t)throw new eG(`missing output at index ${e.output_index}`);if("message"===t.type){let n=t.content[e.content_index];if(!n)throw new eG(`missing content at index ${e.content_index}`);if("output_text"!==n.type)throw new eG(`expected content to be 'output_text', got ${n.type}`);s("response.output_text.delta",{...e,snapshot:n.text})}break}case"response.function_call_arguments.delta":{let t=n.output[e.output_index];if(!t)throw new eG(`missing output at index ${e.output_index}`);"function_call"===t.type&&s("response.function_call_arguments.delta",{...e,snapshot:t.arguments});break}default:s(e.type,e)}},ew=function(){if(this.ended)throw new eG("stream has ended, this shouldn't happen");let e=eK(this,ef,"f");if(!e)throw new eG("request ended without sending any events");eX(this,ef,void 0,"f");let t=function(e,t){var s;return t&&(s=t,si(s.text?.format))?nu(e,t):{...e,output_parsed:null,output:e.output.map(e=>"function_call"===e.type?{...e,parsed_arguments:null}:"message"===e.type?{...e,content:e.content.map(e=>({...e,parsed:null}))}:e)}}(e,eK(this,ep,"f"));return eX(this,em,t,"f"),t},ey=function(e){let t=eK(this,ef,"f");if(!t){if("response.created"!==e.type)throw new eG(`When snapshot hasn't been set yet, expected 'response.created' event, got ${e.type}`);return eX(this,ef,e.response,"f")}switch(e.type){case"response.output_item.added":t.output.push(e.item);break;case"response.content_part.added":{let s=t.output[e.output_index];if(!s)throw new eG(`missing output at index ${e.output_index}`);let n=s.type,r=e.part;"message"===n&&"reasoning_text"!==r.type?s.content.push(r):"reasoning"===n&&"reasoning_text"===r.type&&(s.content||(s.content=[]),s.content.push(r));break}case"response.output_text.delta":{let s=t.output[e.output_index];if(!s)throw new eG(`missing output at index ${e.output_index}`);if("message"===s.type){let t=s.content[e.content_index];if(!t)throw new eG(`missing content at index ${e.content_index}`);if("output_text"!==t.type)throw new eG(`expected content to be 'output_text', got ${t.type}`);t.text+=e.delta}break}case"response.function_call_arguments.delta":{let s=t.output[e.output_index];if(!s)throw new eG(`missing output at index ${e.output_index}`);"function_call"===s.type&&(s.arguments+=e.delta);break}case"response.reasoning_text.delta":{let s=t.output[e.output_index];if(!s)throw new eG(`missing output at index ${e.output_index}`);if("reasoning"===s.type){let t=s.content?.[e.content_index];if(!t)throw new eG(`missing content at index ${e.content_index}`);if("reasoning_text"!==t.type)throw new eG(`expected content to be 'reasoning_text', got ${t.type}`);t.text+=e.delta}break}case"response.completed":eX(this,ef,e.response,"f")}return t},Symbol.asyncIterator)](){let e=[],t=[],s=!1;return this.on("event",s=>{let n=t.shift();n?n.resolve(s):e.push(s)}),this.on("end",()=>{for(let e of(s=!0,t))e.resolve(void 0);t.length=0}),this.on("abort",e=>{for(let n of(s=!0,t))n.reject(e);t.length=0}),this.on("error",e=>{for(let n of(s=!0,t))n.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:s?{value:void 0,done:!0}:new Promise((e,s)=>t.push({resolve:e,reject:s})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();let e=eK(this,em,"f");if(!e)throw new eG("stream ended without producing a ChatCompletion");return e}}class np extends t7{list(e,t={},s){return this._client.getAPIList(ss`/responses/${e}/input_items`,tJ,{query:t,...s})}}class nf extends t7{count(e={},t){return this._client.post("/responses/input_tokens",{body:e,...t})}}class nm extends t7{constructor(){super(...arguments),this.inputItems=new np(this._client),this.inputTokens=new nf(this._client)}create(e,t){return this._client.post("/responses",{body:e,...t,stream:e.stream??!1})._thenUnwrap(e=>("object"in e&&"response"===e.object&&nh(e),e))}retrieve(e,t={},s){return this._client.get(ss`/responses/${e}`,{query:t,...s,stream:t?.stream??!1})._thenUnwrap(e=>("object"in e&&"response"===e.object&&nh(e),e))}delete(e,t){return this._client.delete(ss`/responses/${e}`,{...t,headers:sI([{Accept:"*/*"},t?.headers])})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(t=>nu(t,e))}stream(e,t){return nd.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(ss`/responses/${e}/cancel`,t)}compact(e,t){return this._client.post("/responses/compact",{body:e,...t})}}nm.InputItems=np,nm.InputTokens=nf;class ng extends t7{retrieve(e,t){return this._client.get(ss`/skills/${e}/content`,{...t,headers:sI([{Accept:"application/binary"},t?.headers]),__binaryResponse:!0})}}class n_ extends t7{retrieve(e,t,s){let{skill_id:n}=t;return this._client.get(ss`/skills/${n}/versions/${e}/content`,{...s,headers:sI([{Accept:"application/binary"},s?.headers]),__binaryResponse:!0})}}class nw extends t7{constructor(){super(...arguments),this.content=new n_(this._client)}create(e,t={},s){return this._client.post(ss`/skills/${e}/versions`,tZ({body:t,...s},this._client))}retrieve(e,t,s){let{skill_id:n}=t;return this._client.get(ss`/skills/${n}/versions/${e}`,s)}list(e,t={},s){return this._client.getAPIList(ss`/skills/${e}/versions`,tJ,{query:t,...s})}delete(e,t,s){let{skill_id:n}=t;return this._client.delete(ss`/skills/${n}/versions/${e}`,s)}}nw.Content=n_;class ny extends t7{constructor(){super(...arguments),this.content=new ng(this._client),this.versions=new nw(this._client)}create(e={},t){return this._client.post("/skills",tZ({body:e,...t},this._client))}retrieve(e,t){return this._client.get(ss`/skills/${e}`,t)}update(e,t,s){return this._client.post(ss`/skills/${e}`,{body:t,...s})}list(e={},t){return this._client.getAPIList("/skills",tJ,{query:e,...t})}delete(e,t){return this._client.delete(ss`/skills/${e}`,t)}}ny.Content=ng,ny.Versions=nw;class nb extends t7{create(e,t,s){return this._client.post(ss`/uploads/${e}/parts`,t0({body:t,...s},this._client))}}class nv extends t7{constructor(){super(...arguments),this.parts=new nb(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t})}cancel(e,t){return this._client.post(ss`/uploads/${e}/cancel`,t)}complete(e,t,s){return this._client.post(ss`/uploads/${e}/complete`,{body:t,...s})}}nv.Parts=nb;let nx=async e=>{let t=await Promise.allSettled(e),s=t.filter(e=>"rejected"===e.status);if(s.length){for(let e of s)console.error(e.reason);throw Error(`${s.length} promise(s) failed - see the above errors`)}let n=[];for(let e of t)"fulfilled"===e.status&&n.push(e.value);return n};class nS extends t7{create(e,t,s){return this._client.post(ss`/vector_stores/${e}/file_batches`,{body:t,...s,headers:sI([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}retrieve(e,t,s){let{vector_store_id:n}=t;return this._client.get(ss`/vector_stores/${n}/file_batches/${e}`,{...s,headers:sI([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}cancel(e,t,s){let{vector_store_id:n}=t;return this._client.post(ss`/vector_stores/${n}/file_batches/${e}/cancel`,{...s,headers:sI([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}async createAndPoll(e,t,s){let n=await this.create(e,t);return await this.poll(e,n.id,s)}listFiles(e,t,s){let{vector_store_id:n,...r}=t;return this._client.getAPIList(ss`/vector_stores/${n}/file_batches/${e}/files`,tJ,{query:r,...s,headers:sI([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}async poll(e,t,s){let n=sI([s?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":s?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:r,response:i}=await this.retrieve(t,{vector_store_id:e},{...s,headers:n}).withResponse();switch(r.status){case"in_progress":let a=5e3;if(s?.pollIntervalMs)a=s.pollIntervalMs;else{let e=i.headers.get("openai-poll-after-ms");if(e){let t=parseInt(e);isNaN(t)||(a=t)}}await to(a);break;case"failed":case"cancelled":case"completed":return r}}}async uploadAndPoll(e,{files:t,fileIds:s=[]},n){if(null==t||0==t.length)throw Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let r=Math.min(n?.maxConcurrency??5,t.length),i=this._client,a=t.values(),o=[...s];async function l(e){for(let t of e){let e=await i.files.create({file:t,purpose:"assistants"},n);o.push(e.id)}}let c=Array(r).fill(a).map(l);return await nx(c),await this.createAndPoll(e,{file_ids:o})}}class n$ extends t7{create(e,t,s){return this._client.post(ss`/vector_stores/${e}/files`,{body:t,...s,headers:sI([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}retrieve(e,t,s){let{vector_store_id:n}=t;return this._client.get(ss`/vector_stores/${n}/files/${e}`,{...s,headers:sI([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}update(e,t,s){let{vector_store_id:n,...r}=t;return this._client.post(ss`/vector_stores/${n}/files/${e}`,{body:r,...s,headers:sI([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e,t={},s){return this._client.getAPIList(ss`/vector_stores/${e}/files`,tJ,{query:t,...s,headers:sI([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}delete(e,t,s){let{vector_store_id:n}=t;return this._client.delete(ss`/vector_stores/${n}/files/${e}`,{...s,headers:sI([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}async createAndPoll(e,t,s){let n=await this.create(e,t,s);return await this.poll(e,n.id,s)}async poll(e,t,s){let n=sI([s?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":s?.pollIntervalMs?.toString()??void 0}]);for(;;){let r=await this.retrieve(t,{vector_store_id:e},{...s,headers:n}).withResponse(),i=r.data;switch(i.status){case"in_progress":let a=5e3;if(s?.pollIntervalMs)a=s.pollIntervalMs;else{let e=r.response.headers.get("openai-poll-after-ms");if(e){let t=parseInt(e);isNaN(t)||(a=t)}}await to(a);break;case"failed":case"completed":return i}}}async upload(e,t,s){let n=await this._client.files.create({file:t,purpose:"assistants"},s);return this.create(e,{file_id:n.id},s)}async uploadAndPoll(e,t,s){let n=await this.upload(e,t,s);return await this.poll(e,n.id,s)}content(e,t,s){let{vector_store_id:n}=t;return this._client.getAPIList(ss`/vector_stores/${n}/files/${e}/content`,tK,{...s,headers:sI([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}}class nA extends t7{constructor(){super(...arguments),this.files=new n$(this._client),this.fileBatches=new nS(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:sI([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(ss`/vector_stores/${e}`,{...t,headers:sI([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,s){return this._client.post(ss`/vector_stores/${e}`,{body:t,...s,headers:sI([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e={},t){return this._client.getAPIList("/vector_stores",tJ,{query:e,...t,headers:sI([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(ss`/vector_stores/${e}`,{...t,headers:sI([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}search(e,t,s){return this._client.getAPIList(ss`/vector_stores/${e}/search`,tK,{body:t,method:"post",...s,headers:sI([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}}nA.Files=n$,nA.FileBatches=nS;class nR extends t7{create(e,t){return this._client.post("/videos",tZ({body:e,...t},this._client))}retrieve(e,t){return this._client.get(ss`/videos/${e}`,t)}list(e={},t){return this._client.getAPIList("/videos",tV,{query:e,...t})}delete(e,t){return this._client.delete(ss`/videos/${e}`,t)}downloadContent(e,t={},s){return this._client.get(ss`/videos/${e}/content`,{query:t,...s,headers:sI([{Accept:"application/binary"},s?.headers]),__binaryResponse:!0})}remix(e,t,s){return this._client.post(ss`/videos/${e}/remix`,tZ({body:t,...s},this._client))}}class nI extends t7{constructor(){super(...arguments),eb.add(this)}async unwrap(e,t,s=this._client.webhookSecret,n=300){return await this.verifySignature(e,t,s,n),JSON.parse(e)}async verifySignature(e,t,s=this._client.webhookSecret,n=300){if("u"<typeof crypto||"function"!=typeof crypto.subtle.importKey||"function"!=typeof crypto.subtle.verify)throw Error("Webhook signature verification is only supported when the `crypto` global is defined");eK(this,eb,"m",ev).call(this,s);let r=sI([t]).values,i=eK(this,eb,"m",ex).call(this,r,"webhook-signature"),a=eK(this,eb,"m",ex).call(this,r,"webhook-timestamp"),o=eK(this,eb,"m",ex).call(this,r,"webhook-id"),l=parseInt(a,10);if(isNaN(l))throw new tt("Invalid webhook timestamp format");let c=Math.floor(Date.now()/1e3);if(c-l>n)throw new tt("Webhook timestamp is too old");if(l>c+n)throw new tt("Webhook timestamp is too new");let u=i.split(" ").map(e=>e.startsWith("v1,")?e.substring(3):e),h=s.startsWith("whsec_")?Buffer.from(s.replace("whsec_",""),"base64"):Buffer.from(s,"utf-8"),d=o?`${o}.${a}.${e}`:`${a}.${e}`,p=await crypto.subtle.importKey("raw",h,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let e of u)try{let t=Buffer.from(e,"base64");if(await crypto.subtle.verify("HMAC",p,t,new TextEncoder().encode(d)))return}catch{continue}throw new tt("The given webhook signature does not match the expected signature")}}eb=new WeakSet,ev=function(e){if("string"!=typeof e||0===e.length)throw 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")},ex=function(e,t){if(!e)throw Error("Headers are required");let s=e.get(t);if(null==s)throw Error(`Missing required header: ${t}`);return s},e.i(98546);class nO{constructor({baseURL:e=sU("OPENAI_BASE_URL"),apiKey:t=sU("OPENAI_API_KEY"),organization:s=sU("OPENAI_ORG_ID")??null,project:n=sU("OPENAI_PROJECT_ID")??null,webhookSecret:r=sU("OPENAI_WEBHOOK_SECRET")??null,...i}={}){if(eS.add(this),eA.set(this,void 0),this.completions=new sJ(this),this.chat=new sA(this),this.embeddings=new sZ(this),this.files=new s4(this),this.images=new nr(this),this.audio=new sP(this),this.moderations=new na(this),this.models=new ni(this),this.fineTuning=new nt(this),this.graders=new nn(this),this.vectorStores=new nA(this),this.webhooks=new nI(this),this.beta=new sK(this),this.batches=new sC(this),this.uploads=new nv(this),this.responses=new nm(this),this.realtime=new nc(this),this.conversations=new sY(this),this.evals=new s2(this),this.containers=new sG(this),this.skills=new ny(this),this.videos=new nR(this),void 0===t)throw new eG("Missing credentials. Please pass an `apiKey`, or set the `OPENAI_API_KEY` environment variable.");const a={apiKey:t,organization:s,project:n,webhookSecret:r,...i,baseURL:e||"https://api.openai.com/v1"};a.dangerouslyAllowBrowser,this.baseURL=a.baseURL,this.timeout=a.timeout??e$.DEFAULT_TIMEOUT,this.logger=a.logger??console;const o="warn";this.logLevel=o,this.logLevel=tk(a.logLevel,"ClientOptions.logLevel",this)??tk(sU("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??o,this.fetchOptions=a.fetchOptions,this.maxRetries=a.maxRetries??2,this.fetch=a.fetch??function(){if("u">typeof fetch)return fetch;throw Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}(),eX(this,eA,tm,"f"),this._options=a,this.apiKey="string"==typeof t?t:"Missing Key",this.organization=s,this.project=n,this.webhookSecret=r}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 sI([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return function(e,t={}){let s,n=e,r=function(e=t$){let t;if(void 0!==e.allowEmptyArrays&&"boolean"!=typeof e.allowEmptyArrays)throw TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(void 0!==e.encodeDotInKeys&&"boolean"!=typeof e.encodeDotInKeys)throw TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(null!==e.encoder&&void 0!==e.encoder&&"function"!=typeof e.encoder)throw TypeError("Encoder has to be a function.");let s=e.charset||t$.charset;if(void 0!==e.charset&&"utf-8"!==e.charset&&"iso-8859-1"!==e.charset)throw TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let n=tg;if(void 0!==e.format){if(!ty(tw,e.format))throw TypeError("Unknown format option provided.");n=e.format}let r=tw[n],i=t$.filter;if(("function"==typeof e.filter||tn(e.filter))&&(i=e.filter),t=e.arrayFormat&&e.arrayFormat in tx?e.arrayFormat:"indices"in e?e.indices?"indices":"repeat":t$.arrayFormat,"commaRoundTrip"in e&&"boolean"!=typeof e.commaRoundTrip)throw TypeError("`commaRoundTrip` must be a boolean, or absent");let a=void 0===e.allowDots?!0==!!e.encodeDotInKeys||t$.allowDots:!!e.allowDots;return{addQueryPrefix:"boolean"==typeof e.addQueryPrefix?e.addQueryPrefix:t$.addQueryPrefix,allowDots:a,allowEmptyArrays:"boolean"==typeof e.allowEmptyArrays?!!e.allowEmptyArrays:t$.allowEmptyArrays,arrayFormat:t,charset:s,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:t$.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:void 0===e.delimiter?t$.delimiter:e.delimiter,encode:"boolean"==typeof e.encode?e.encode:t$.encode,encodeDotInKeys:"boolean"==typeof e.encodeDotInKeys?e.encodeDotInKeys:t$.encodeDotInKeys,encoder:"function"==typeof e.encoder?e.encoder:t$.encoder,encodeValuesOnly:"boolean"==typeof e.encodeValuesOnly?e.encodeValuesOnly:t$.encodeValuesOnly,filter:i,format:n,formatter:r,serializeDate:"function"==typeof e.serializeDate?e.serializeDate:t$.serializeDate,skipNulls:"boolean"==typeof e.skipNulls?e.skipNulls:t$.skipNulls,sort:"function"==typeof e.sort?e.sort:null,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:t$.strictNullHandling}}(t);"function"==typeof r.filter?n=(0,r.filter)("",n):tn(r.filter)&&(s=r.filter);let i=[];if("object"!=typeof n||null===n)return"";let a=tx[r.arrayFormat],o="comma"===a&&r.commaRoundTrip;s||(s=Object.keys(n)),r.sort&&s.sort(r.sort);let l=new WeakMap;for(let e=0;e<s.length;++e){let t=s[e];r.skipNulls&&null===n[t]||tS(i,function e(t,s,n,r,i,a,o,l,c,u,h,d,p,f,m,g,_,w){var y,b;let v,x=t,S=w,$=0,A=!1;for(;void 0!==(S=S.get(tA))&&!A;){let e=S.get(t);if($+=1,void 0!==e)if(e===$)throw RangeError("Cyclic object value");else A=!0;void 0===S.get(tA)&&($=0)}if("function"==typeof u?x=u(s,x):x instanceof Date?x=p?.(x):"comma"===n&&tn(x)&&(x=tv(x,function(e){return e instanceof Date?p?.(e):e})),null===x){if(a)return c&&!g?c(s,t$.encoder,_,"key",f):s;x=""}if("string"==typeof(y=x)||"number"==typeof y||"boolean"==typeof y||"symbol"==typeof y||"bigint"==typeof y||(b=x)&&"object"==typeof b&&b.constructor&&b.constructor.isBuffer&&b.constructor.isBuffer(b)){if(c){let e=g?s:c(s,t$.encoder,_,"key",f);return[m?.(e)+"="+m?.(c(x,t$.encoder,_,"value",f))]}return[m?.(s)+"="+m?.(String(x))]}let R=[];if(void 0===x)return R;if("comma"===n&&tn(x))g&&c&&(x=tv(x,c)),v=[{value:x.length>0?x.join(",")||null:void 0}];else if(tn(u))v=u;else{let e=Object.keys(x);v=h?e.sort(h):e}let I=l?String(s).replace(/\./g,"%2E"):String(s),O=r&&tn(x)&&1===x.length?I+"[]":I;if(i&&tn(x)&&0===x.length)return O+"[]";for(let s=0;s<v.length;++s){let y=v[s],b="object"==typeof y&&void 0!==y.value?y.value:x[y];if(o&&null===b)continue;let S=d&&l?y.replace(/\./g,"%2E"):y,A=tn(x)?"function"==typeof n?n(O,S):O:O+(d?"."+S:"["+S+"]");w.set(t,$);let I=new WeakMap;I.set(tA,w),tS(R,e(b,A,n,r,i,a,o,l,"comma"===n&&g&&tn(x)?null:c,u,h,d,p,f,m,g,_,I))}return R}(n[t],t,a,o,r.allowEmptyArrays,r.strictNullHandling,r.skipNulls,r.encodeDotInKeys,r.encode?r.encoder:null,r.filter,r.sort,r.allowDots,r.serializeDate,r.format,r.formatter,r.encodeValuesOnly,r.charset,l))}let c=i.join(r.delimiter),u=!0===r.addQueryPrefix?"?":"";return r.charsetSentinel&&("iso-8859-1"===r.charset?u+="utf8=%26%2310003%3B&":u+="utf8=%E2%9C%93&"),c.length>0?u+c:""}(e,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${tl}`}defaultIdempotencyKey(){return`stainless-node-retry-${eJ()}`}makeStatusError(e,t,s,n){return eQ.generate(e,t,s,n)}async _callApiKey(){let e,t=this._options.apiKey;if("function"!=typeof t)return!1;try{e=await t()}catch(e){if(e instanceof eG)throw e;throw new eG(`Failed to get token from 'apiKey' function: ${e.message}`,{cause:e})}if("string"!=typeof e||!e)throw new eG(`Expected 'apiKey' function argument to return a string but it returned ${e}`);return this.apiKey=e,!0}buildURL(e,t,s){let n=!eK(this,eS,"m",eR).call(this)&&s||this.baseURL,r=new URL(ts.test(e)?e:n+(n.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),i=this.defaultQuery();return!function(e){if(!e)return!0;for(let t in e)return!1;return!0}(i)&&(t={...i,...t}),"object"==typeof t&&t&&!Array.isArray(t)&&(r.search=this.stringifyQuery(t)),r.toString()}async prepareOptions(e){await this._callApiKey()}async prepareRequest(e,{url:t,options:s}){}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,s){return this.request(Promise.resolve(s).then(s=>({method:e,path:t,...s})))}request(e,t=null){return new tH(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,s){let n=await e,r=n.maxRetries??this.maxRetries;null==t&&(t=r),await this.prepareOptions(n);let{req:i,url:a,timeout:o}=await this.buildRequest(n,{retryCount:r-t});await this.prepareRequest(i,{url:a,options:n});let l="log_"+(0x1000000*Math.random()|0).toString(16).padStart(6,"0"),c=void 0===s?"":`, retryOf: ${s}`,u=Date.now();if(tj(this).debug(`[${l}] sending request`,tM({retryOfRequestLogID:s,method:n.method,url:a,options:n,headers:i.headers})),n.signal?.aborted)throw new eY;let h=new AbortController,d=await this.fetchWithTimeout(a,i,o,h).catch(ez),p=Date.now();if(d instanceof globalThis.Error){let e=`retrying, ${t} attempts remaining`;if(n.signal?.aborted)throw new eY;let r=eV(d)||/timed? ?out/i.test(String(d)+("cause"in d?String(d.cause):""));if(t)return tj(this).info(`[${l}] connection ${r?"timed out":"failed"} - ${e}`),tj(this).debug(`[${l}] connection ${r?"timed out":"failed"} (${e})`,tM({retryOfRequestLogID:s,url:a,durationMs:p-u,message:d.message})),this.retryRequest(n,t,s??l);if(tj(this).info(`[${l}] connection ${r?"timed out":"failed"} - error; no more retries left`),tj(this).debug(`[${l}] connection ${r?"timed out":"failed"} (error; no more retries left)`,tM({retryOfRequestLogID:s,url:a,durationMs:p-u,message:d.message})),r)throw new e0;throw new eZ({cause:d})}let f=[...d.headers.entries()].filter(([e])=>"x-request-id"===e).map(([e,t])=>", "+e+": "+JSON.stringify(t)).join(""),m=`[${l}${c}${f}] ${i.method} ${a} ${d.ok?"succeeded":"failed"} with status ${d.status} in ${p-u}ms`;if(!d.ok){let e=await this.shouldRetry(d);if(t&&e){let e=`retrying, ${t} attempts remaining`;return await tf(d.body),tj(this).info(`${m} - ${e}`),tj(this).debug(`[${l}] response error (${e})`,tM({retryOfRequestLogID:s,url:d.url,status:d.status,headers:d.headers,durationMs:p-u})),this.retryRequest(n,t,s??l,d.headers)}let r=e?"error; no more retries left":"error; not retryable";tj(this).info(`${m} - ${r}`);let i=await d.text().catch(e=>ez(e).message),a=(e=>{try{return JSON.parse(e)}catch(e){return}})(i),o=a?void 0:i;throw tj(this).debug(`[${l}] response error (${r})`,tM({retryOfRequestLogID:s,url:d.url,status:d.status,headers:d.headers,message:o,durationMs:Date.now()-u})),this.makeStatusError(d.status,a,o,d.headers)}return tj(this).info(m),tj(this).debug(`[${l}] response start`,tM({retryOfRequestLogID:s,url:d.url,status:d.status,headers:d.headers,durationMs:p-u})),{response:d,options:n,controller:h,requestLogID:l,retryOfRequestLogID:s,startTime:u}}getAPIList(e,t,s){return this.requestAPIList(t,s&&"then"in s?s.then(t=>({method:"get",path:e,...t})):{method:"get",path:e,...s})}requestAPIList(e,t){return new tX(this,this.makeRequest(t,null,void 0),e)}async fetchWithTimeout(e,t,s,n){let{signal:r,method:i,...a}=t||{},o=this._makeAbort(n);r&&r.addEventListener("abort",o,{once:!0});let l=setTimeout(o,s),c=globalThis.ReadableStream&&a.body instanceof globalThis.ReadableStream||"object"==typeof a.body&&null!==a.body&&Symbol.asyncIterator in a.body,u={signal:n.signal,...c?{duplex:"half"}:{},method:"GET",...a};i&&(u.method=i.toUpperCase());try{return await this.fetch.call(void 0,e,u)}finally{clearTimeout(l)}}async shouldRetry(e){let t=e.headers.get("x-should-retry");return"true"===t||"false"!==t&&(408===e.status||409===e.status||429===e.status||!!(e.status>=500))}async retryRequest(e,t,s,n){let r,i=n?.get("retry-after-ms");if(i){let e=parseFloat(i);Number.isNaN(e)||(r=e)}let a=n?.get("retry-after");if(a&&!r){let e=parseFloat(a);r=Number.isNaN(e)?Date.parse(a)-Date.now():1e3*e}if(!(r&&0<=r&&r<6e4)){let s=e.maxRetries??this.maxRetries;r=this.calculateDefaultRetryTimeoutMillis(t,s)}return await to(r),this.makeRequest(e,t-1,s)}calculateDefaultRetryTimeoutMillis(e,t){return Math.min(.5*Math.pow(2,t-e),8)*(1-.25*Math.random())*1e3}async buildRequest(e,{retryCount:t=0}={}){let s={...e},{method:n,path:r,query:i,defaultBaseURL:a}=s,o=this.buildURL(r,i,a);"timeout"in s&&((e,t)=>{if("number"!=typeof t||!Number.isInteger(t))throw new eG(`${e} must be an integer`);if(t<0)throw new eG(`${e} must be a positive integer`)})("timeout",s.timeout),s.timeout=s.timeout??this.timeout;let{bodyHeaders:l,body:c}=this.buildBody({options:s}),u=await this.buildHeaders({options:e,method:n,bodyHeaders:l,retryCount:t});return{req:{method:n,headers:u,...s.signal&&{signal:s.signal},...globalThis.ReadableStream&&c instanceof globalThis.ReadableStream&&{duplex:"half"},...c&&{body:c},...this.fetchOptions??{},...s.fetchOptions??{}},url:o,timeout:s.timeout}}async buildHeaders({options:e,method:s,bodyHeaders:n,retryCount:r}){let i={};this.idempotencyHeader&&"get"!==s&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),i[this.idempotencyHeader]=e.idempotencyKey);let a=sI([i,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(r),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...t??(t=(()=>{let e="u">typeof Deno&&null!=Deno.build?"deno":"u">typeof EdgeRuntime?"edge":"[object process]"===Object.prototype.toString.call(void 0!==globalThis.process?globalThis.process:0)?"node":"unknown";if("deno"===e)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":tl,"X-Stainless-OS":tu(Deno.build.os),"X-Stainless-Arch":tc(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":"string"==typeof Deno.version?Deno.version:Deno.version?.deno??"unknown"};if("u">typeof EdgeRuntime)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":tl,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if("node"===e)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":tl,"X-Stainless-OS":tu(globalThis.process.platform??"unknown"),"X-Stainless-Arch":tc(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let t=function(){if("u"<typeof navigator||!navigator)return null;for(let{key:e,pattern:t}of[{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/}]){let s=t.exec(navigator.userAgent);if(s){let t=s[1]||0,n=s[2]||0,r=s[3]||0;return{browser:e,version:`${t}.${n}.${r}`}}}return null}();return t?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":tl,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":tl,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}})()),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(a),a.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};let s=sI([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||"string"==typeof e&&s.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:"object"==typeof e&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&"function"==typeof e.next)?{bodyHeaders:void 0,body:td(e)}:"object"==typeof e&&"application/x-www-form-urlencoded"===s.values.get("content-type")?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(e)}:eK(this,eA,"f").call(this,{body:e,headers:s})}}e$=nO,eA=new WeakMap,eS=new WeakSet,eR=function(){return"https://api.openai.com/v1"!==this.baseURL},nO.OpenAI=e$,nO.DEFAULT_TIMEOUT=6e5,nO.OpenAIError=eG,nO.APIError=eQ,nO.APIConnectionError=eZ,nO.APIConnectionTimeoutError=e0,nO.APIUserAbortError=eY,nO.NotFoundError=e6,nO.ConflictError=e3,nO.RateLimitError=e5,nO.BadRequestError=e1,nO.AuthenticationError=e2,nO.InternalServerError=e9,nO.PermissionDeniedError=e4,nO.UnprocessableEntityError=e8,nO.InvalidWebhookSignatureError=tt,nO.toFile=t5,nO.Completions=sJ,nO.Chat=sA,nO.Embeddings=sZ,nO.Files=s4,nO.Images=nr,nO.Audio=sP,nO.Moderations=na,nO.Models=ni,nO.FineTuning=nt,nO.Graders=nn,nO.VectorStores=nA,nO.Webhooks=nI,nO.Beta=sK,nO.Batches=sC,nO.Uploads=nv,nO.Responses=nm,nO.Realtime=nc,nO.Conversations=sY,nO.Evals=s2,nO.Containers=sG,nO.Skills=ny,nO.Videos=nR;var nE=e.i(22734),nk=e.i(14747),nP=e.i(33405),nC=e.i(7367);let nT=null,nN=!1,nj={};async function nM(){if(nN)return nj;nN=!0;try{let e=nk.default.join((0,nC.getSlycodeRoot)(),".env");for(let t of(await nE.promises.readFile(e,"utf-8")).split("\n")){let e=t.match(/^([A-Z_]+)=(.+)$/);e&&(nj[e[1]]=e[2].trim(),new Set(["BRIDGE_URL","BRIDGE_PORT","WEB_PORT","MESSAGING_SERVICE_PORT"]).has(e[1])||process.env[e[1]]||(process.env[e[1]]=nj[e[1]]))}}catch{}return nj}async function nD(){if(!nT){let e=await nM(),t=process.env.OPENAI_API_KEY||e.OPENAI_API_KEY;if(!t)throw Error("OPENAI_API_KEY not configured");nT=new nO({apiKey:t})}return nT}function nL(e,t,s){return new Promise((n,r)=>{(0,nP.execFile)(e,t,{...s,windowsHide:!0},(e,t,s)=>{e?r(Error(`${e.message}
9
- ${s}`)):n("string"==typeof t?t:String(t))})})}async function nB(e,t,s,n){let r=process.env.TMPDIR||"/tmp",i=nk.default.join(r,`whisper_${Date.now()}.${t}`),a=i.replace(/\.[^.]+$/,".wav");try{return await nE.promises.writeFile(i,e),await nL("ffmpeg",["-i",i,"-ar","16000","-ac","1","-y",a],{timeout:3e4}),(await nL(s,["-m",n,"-f",a,"--no-timestamps","--output-txt"],{timeout:12e4,encoding:"utf-8"})).trim()}finally{await nE.promises.unlink(i).catch(()=>{}),await nE.promises.unlink(a).catch(()=>{})}}async function nW(e){try{let t,s=(await e.formData()).get("audio");if(!s||!(s instanceof Blob))return eF.NextResponse.json({error:'Missing "audio" file in form data'},{status:400});let n=Buffer.from(await s.arrayBuffer()),r=s.type.includes("mp4")?"mp4":s.type.includes("ogg")?"ogg":"webm",i=await nM(),a=process.env.STT_BACKEND||i.STT_BACKEND||"openai";if("local"===a){let e=process.env.WHISPER_CLI_PATH||i.WHISPER_CLI_PATH,t=process.env.WHISPER_MODEL_PATH||i.WHISPER_MODEL_PATH;if(!e||!t)return eF.NextResponse.json({error:"Local STT not configured: set WHISPER_CLI_PATH and WHISPER_MODEL_PATH"},{status:401});let s=await nB(n,r,e,t);return eF.NextResponse.json({text:s})}try{t=await nD()}catch{return eF.NextResponse.json({error:"OPENAI_API_KEY not configured"},{status:401})}let o=await t5(n,`recording.${r}`,{type:s.type}),l=await t.audio.transcriptions.create({file:o,model:"whisper-1"});return eF.NextResponse.json({text:l.text})}catch(t){let e=t.message||"Transcription failed";return eF.NextResponse.json({error:e},{status:502})}}e.s(["POST",()=>nW],14779);var nq=e.i(14779);let nU=new eI.AppRouteRouteModule({definition:{kind:eO.RouteKind.APP_ROUTE,page:"/api/transcribe/route",pathname:"/api/transcribe",filename:"route",bundlePath:""},distDir:".next",relativeProjectDir:"",resolvedPagePath:"[project]/src/app/api/transcribe/route.ts",nextConfigOutput:"standalone",userland:nq}),{workAsyncStorage:nH,workUnitAsyncStorage:nF,serverHooks:nX}=nU;function nK(){return(0,eE.patchFetch)({workAsyncStorage:nH,workUnitAsyncStorage:nF})}async function nJ(e,t,s){nU.isDev&&(0,ek.addRequestMeta)(e,"devRequestTimingInternalsEnd",process.hrtime.bigint());let n="/api/transcribe/route";n=n.replace(/\/index$/,"")||"/";let r=await nU.prepare(e,t,{srcPage:n,multiZoneDraftMode:!1});if(!r)return t.statusCode=400,t.end("Bad Request"),null==s.waitUntil||s.waitUntil.call(s,Promise.resolve()),null;let{buildId:i,params:a,nextConfig:o,parsedUrl:l,isDraftMode:c,prerenderManifest:u,routerServerContext:h,isOnDemandRevalidate:d,revalidateOnlyGenerated:p,resolvedPathname:f,clientReferenceManifest:m,serverActionsManifest:g}=r,_=(0,eT.normalizeAppPath)(n),w=!!(u.dynamicRoutes[_]||u.routes[f]),y=async()=>((null==h?void 0:h.render404)?await h.render404(e,t,l,!1):t.end("This page could not be found"),null);if(w&&!c){let e=!!u.routes[f],t=u.dynamicRoutes[_];if(t&&!1===t.fallback&&!e){if(o.experimental.adapterPath)return await y();throw new eU.NoFallbackError}}let b=null;!w||nU.isDev||c||(b="/index"===(b=f)?"/":b);let v=!0===nU.isDev||!w,x=w&&!v;g&&m&&(0,eC.setManifestsSingleton)({page:n,clientReferenceManifest:m,serverActionsManifest:g});let S=e.method||"GET",$=(0,eP.getTracer)(),A=$.getActiveScopeSpan(),R={params:a,prerenderManifest:u,renderOpts:{experimental:{authInterrupts:!!o.experimental.authInterrupts},cacheComponents:!!o.cacheComponents,supportsDynamicResponse:v,incrementalCache:(0,ek.getRequestMeta)(e,"incrementalCache"),cacheLifeProfiles:o.cacheLife,waitUntil:s.waitUntil,onClose:e=>{t.on("close",e)},onAfterTaskError:void 0,onInstrumentationRequestError:(t,s,n,r)=>nU.onRequestError(e,t,n,r,h)},sharedContext:{buildId:i}},I=new eN.NodeNextRequest(e),O=new eN.NodeNextResponse(t),E=ej.NextRequestAdapter.fromNodeNextRequest(I,(0,ej.signalFromNodeResponse)(t));try{let r=async e=>nU.handle(E,R).finally(()=>{if(!e)return;e.setAttributes({"http.status_code":t.statusCode,"next.rsc":!1});let s=$.getRootSpanAttributes();if(!s)return;if(s.get("next.span_type")!==eM.BaseServerSpan.handleRequest)return void console.warn(`Unexpected root span type '${s.get("next.span_type")}'. Please report this Next.js issue https://github.com/vercel/next.js`);let r=s.get("next.route");if(r){let t=`${S} ${r}`;e.setAttributes({"next.route":r,"http.route":r,"next.span_name":t}),e.updateName(t)}else e.updateName(`${S} ${n}`)}),i=!!(0,ek.getRequestMeta)(e,"minimalMode"),a=async a=>{var l,f;let m=async({previousCacheEntry:o})=>{try{if(!i&&d&&p&&!o)return t.statusCode=404,t.setHeader("x-nextjs-cache","REVALIDATED"),t.end("This page could not be found"),null;let n=await r(a);e.fetchMetrics=R.renderOpts.fetchMetrics;let l=R.renderOpts.pendingWaitUntil;l&&s.waitUntil&&(s.waitUntil(l),l=void 0);let c=R.renderOpts.collectedTags;if(!w)return await (0,eL.sendResponse)(I,O,n,R.renderOpts.pendingWaitUntil),null;{let e=await n.blob(),t=(0,eB.toNodeOutgoingHttpHeaders)(n.headers);c&&(t[eq.NEXT_CACHE_TAGS_HEADER]=c),!t["content-type"]&&e.type&&(t["content-type"]=e.type);let s=void 0!==R.renderOpts.collectedRevalidate&&!(R.renderOpts.collectedRevalidate>=eq.INFINITE_CACHE)&&R.renderOpts.collectedRevalidate,r=void 0===R.renderOpts.collectedExpire||R.renderOpts.collectedExpire>=eq.INFINITE_CACHE?void 0:R.renderOpts.collectedExpire;return{value:{kind:eH.CachedRouteKind.APP_ROUTE,status:n.status,body:Buffer.from(await e.arrayBuffer()),headers:t},cacheControl:{revalidate:s,expire:r}}}}catch(t){throw(null==o?void 0:o.isStale)&&await nU.onRequestError(e,t,{routerKind:"App Router",routePath:n,routeType:"route",revalidateReason:(0,eD.getRevalidateReason)({isStaticGeneration:x,isOnDemandRevalidate:d})},!1,h),t}},g=await nU.handleResponse({req:e,nextConfig:o,cacheKey:b,routeKind:eO.RouteKind.APP_ROUTE,isFallback:!1,prerenderManifest:u,isRoutePPREnabled:!1,isOnDemandRevalidate:d,revalidateOnlyGenerated:p,responseGenerator:m,waitUntil:s.waitUntil,isMinimalMode:i});if(!w)return null;if((null==g||null==(l=g.value)?void 0:l.kind)!==eH.CachedRouteKind.APP_ROUTE)throw Object.defineProperty(Error(`Invariant: app-route received invalid cache entry ${null==g||null==(f=g.value)?void 0:f.kind}`),"__NEXT_ERROR_CODE",{value:"E701",enumerable:!1,configurable:!0});i||t.setHeader("x-nextjs-cache",d?"REVALIDATED":g.isMiss?"MISS":g.isStale?"STALE":"HIT"),c&&t.setHeader("Cache-Control","private, no-cache, no-store, max-age=0, must-revalidate");let _=(0,eB.fromNodeOutgoingHttpHeaders)(g.value.headers);return i&&w||_.delete(eq.NEXT_CACHE_TAGS_HEADER),!g.cacheControl||t.getHeader("Cache-Control")||_.get("Cache-Control")||_.set("Cache-Control",(0,eW.getCacheControlHeader)(g.cacheControl)),await (0,eL.sendResponse)(I,O,new Response(g.value.body,{headers:_,status:g.value.status||200})),null};A?await a(A):await $.withPropagatedContext(e.headers,()=>$.trace(eM.BaseServerSpan.handleRequest,{spanName:`${S} ${n}`,kind:eP.SpanKind.SERVER,attributes:{"http.method":S,"http.target":e.url}},a))}catch(t){if(t instanceof eU.NoFallbackError||await nU.onRequestError(e,t,{routerKind:"App Router",routePath:_,routeType:"route",revalidateReason:(0,eD.getRevalidateReason)({isStaticGeneration:x,isOnDemandRevalidate:d})},!1,h),w)throw t;return await (0,eL.sendResponse)(I,O,new Response(null,{status:500})),null}}e.s(["handler",()=>nJ,"patchFetch",()=>nK,"routeModule",()=>nU,"serverHooks",()=>nX,"workAsyncStorage",()=>nH,"workUnitAsyncStorage",()=>nF],99567)}];
10
-
11
- //# sourceMappingURL=node_modules_next_dist_esm_build_templates_app-route_ffc6c790.js.map
@@ -1,3 +0,0 @@
1
- module.exports=[56704,(a,b,c)=>{b.exports=a.x("next/dist/server/app-render/work-async-storage.external.js",()=>require("next/dist/server/app-render/work-async-storage.external.js"))},32319,(a,b,c)=>{b.exports=a.x("next/dist/server/app-render/work-unit-async-storage.external.js",()=>require("next/dist/server/app-render/work-unit-async-storage.external.js"))},20635,(a,b,c)=>{b.exports=a.x("next/dist/server/app-render/action-async-storage.external.js",()=>require("next/dist/server/app-render/action-async-storage.external.js"))},9270,(a,b,c)=>{"use strict";b.exports=a.r(42602).vendored.contexts.AppRouterContext},38783,(a,b,c)=>{"use strict";b.exports=a.r(42602).vendored["react-ssr"].ReactServerDOMTurbopackClient},36313,(a,b,c)=>{"use strict";b.exports=a.r(42602).vendored.contexts.HooksClientContext},18341,(a,b,c)=>{"use strict";b.exports=a.r(42602).vendored.contexts.ServerInsertedHtml},10123,a=>{"use strict";let b="slycode:terminal-prompt";function c(a,d=!0){let e=new CustomEvent(b,{detail:{prompt:a,autoSubmit:d}});window.dispatchEvent(e)}function d(a){let c=b=>{a(b.detail)};return window.addEventListener(b,c),()=>window.removeEventListener(b,c)}a.s(["onTerminalPrompt",()=>d,"pushToTerminal",()=>c])}];
2
-
3
- //# sourceMappingURL=%5Broot-of-the-server%5D__73cfc6bb._.js.map