alran 0.0.0-stage → 1.0.1

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 (505) hide show
  1. package/ALRAN_TOOLS_NOTICES.md +75 -0
  2. package/LICENSE +27 -0
  3. package/LICENSE-STATUS.md +21 -0
  4. package/NOTICE +6 -0
  5. package/README.md +284 -2
  6. package/THIRD_PARTY_NOTICES.md +113 -0
  7. package/alran-tools.js +3 -0
  8. package/assets/agents/_default/prompt-auto_classifier.md +185 -0
  9. package/assets/agents/_default/prompt-auto_classifier_extras.md +17 -0
  10. package/assets/agents/_default/prompt-base-all.md +133 -0
  11. package/assets/agents/_default/prompt-base-all.md.hbs +228 -0
  12. package/assets/agents/_default/prompt-base-windows.md +5 -0
  13. package/assets/agents/_default/prompt-base-windows.md.hbs +5 -0
  14. package/assets/agents/_default/prompt-base-worker.md +10 -0
  15. package/assets/agents/_default/prompt-base-worker.md.hbs +27 -0
  16. package/assets/agents/_default/prompt-compact.md +76 -0
  17. package/assets/agents/_default/prompt-compact_continue.md +9 -0
  18. package/assets/agents/_default/prompt-git.md +8 -0
  19. package/assets/agents/_default/prompt-goal.md +13 -0
  20. package/assets/agents/_default/prompt-session-branch.md +3 -0
  21. package/assets/agents/_default/prompt-session-branch.md.hbs +30 -0
  22. package/assets/agents/_default/prompt-session-root.md +3 -0
  23. package/assets/agents/_default/prompt-session-root.md.hbs +32 -0
  24. package/assets/agents/_default/prompt-title.md +11 -0
  25. package/assets/agents/_default/prompt-tool_agent.md +22 -0
  26. package/assets/agents/_migration/README.md +20 -0
  27. package/assets/agents/_migration/coder/PERSONA.md +11 -0
  28. package/assets/agents/_migration/coder/system-prompt.md.hbs +42 -0
  29. package/assets/agents/_migration/general/PERSONA.md +11 -0
  30. package/assets/agents/_migration/general/system-prompt.md.hbs +49 -0
  31. package/assets/agents/_v2/AGENT_CONTEXT.md.hbs +245 -0
  32. package/assets/agents/_v2/PTC_TOOL_CALLS.md.hbs +35 -0
  33. package/assets/agents/_v2/coding/SYSTEM.md.hbs +173 -0
  34. package/assets/agents/_v2/explore.md.hbs +38 -0
  35. package/assets/agents/_v2/tui/SYSTEM.md.hbs +211 -0
  36. package/assets/agents/_v2/verifier.md.hbs +32 -0
  37. package/assets/agents/_v2/work/SYSTEM.md.hbs +186 -0
  38. package/assets/agents/_v2/worker.md.hbs +27 -0
  39. package/assets/agents/alran/PERSONA.md +7 -0
  40. package/assets/agents/alran/features/cron.md.hbs +0 -0
  41. package/assets/agents/alran/features/delegation.md.hbs +56 -0
  42. package/assets/agents/alran/features/memory.md.hbs +61 -0
  43. package/assets/agents/alran/features/recoverable-deletion.md.hbs +10 -0
  44. package/assets/agents/alran/features/task-management.md.hbs +11 -0
  45. package/assets/agents/alran/features/web-search.md.hbs +11 -0
  46. package/assets/agents/alran/modes/coding/online/PERSONA.md.hbs +20 -0
  47. package/assets/agents/alran/modes/coding/online/SYSTEM.md.hbs +158 -0
  48. package/assets/agents/alran/modes/work/online/PERSONA.md.hbs +20 -0
  49. package/assets/agents/alran/modes/work/online/SYSTEM.md.hbs +160 -0
  50. package/assets/agents/alran/prompt-session-root.md +4 -0
  51. package/assets/agents/alran/prompt-session-root.md.hbs +4 -0
  52. package/assets/agents/alran/skills/alran-code-product/SKILL.md +72 -0
  53. package/assets/agents/alran/skills/alran-code-product/references/account-models.md +64 -0
  54. package/assets/agents/alran/skills/alran-code-product/references/agents.md +34 -0
  55. package/assets/agents/alran/skills/alran-code-product/references/extensions.md +46 -0
  56. package/assets/agents/alran/skills/alran-code-product/references/workflows.md +56 -0
  57. package/assets/agents/alran/skills/control-in-app-browser/SKILL.md +590 -0
  58. package/assets/agents/alran/system-prompt.md.hbs +97 -0
  59. package/assets/agents/builtin-agents.json +1 -0
  60. package/assets/agents/desktop-task/archive-title/system-en.md +1 -0
  61. package/assets/agents/desktop-task/checkpoint/system.md +19 -0
  62. package/assets/agents/desktop-task/output-revision/system.md +1 -0
  63. package/assets/agents/desktop-task/retry/continuation.md +4 -0
  64. package/assets/agents/desktop-task/session-title/system.md +41 -0
  65. package/assets/agents/explore/PERSONA.md +8 -0
  66. package/assets/agents/explore/agent.md +14 -0
  67. package/assets/agents/explore/system-prompt.md.hbs +35 -0
  68. package/assets/agents/greeting.md +61 -0
  69. package/assets/agents/managed-prompts.json +47 -0
  70. package/assets/agents/prompt-exemptions.json +36 -0
  71. package/assets/agents/verifier/PERSONA.md +8 -0
  72. package/assets/agents/verifier/agent.md +17 -0
  73. package/assets/agents/verifier/system-prompt.md.hbs +28 -0
  74. package/assets/agents/worker/PERSONA.md +8 -0
  75. package/assets/agents/worker/agent.md +18 -0
  76. package/assets/agents/worker/system-prompt.md.hbs +22 -0
  77. package/assets/agents/workflow/code-review/review-candidates.md +120 -0
  78. package/assets/agents/workflow/code-review/reviewer-system.md +75 -0
  79. package/assets/agents/workflow/goal/budget-limit.md +16 -0
  80. package/assets/agents/workflow/goal/continuation.md +62 -0
  81. package/assets/agents/workflow/goal/objective-updated.md +16 -0
  82. package/assets/agents/workflow/goal/recovery-terminal-audit.md +13 -0
  83. package/assets/agents/workflow/goal/recovery.md +11 -0
  84. package/assets/agents/workflow/goal/terminal-audit.md +10 -0
  85. package/assets/agents/workflow/plan-mode/agent-entry.md +72 -0
  86. package/assets/agents/workflow/prompt-hook/system.md +0 -0
  87. package/assets/models-dev-catalog.json.gz +0 -0
  88. package/assets/prompts/code-review/review-candidates.md +120 -0
  89. package/assets/prompts/code-review/reviewer-system.md +75 -0
  90. package/assets/skills/alran-tools-master/SKILL.md +127 -0
  91. package/assets/skills/code-review/SKILL.md +51 -0
  92. package/assets/skills/cu-desktop/SKILL.md +255 -0
  93. package/assets/skills/deep-research/SKILL.md +30 -0
  94. package/assets/skills/deploy-website/SKILL.md +52 -0
  95. package/assets/skills/docx/LICENSE +21 -0
  96. package/assets/skills/docx/SKILL.md +259 -0
  97. package/assets/skills/docx/assets/styles/academic_styles.xml +250 -0
  98. package/assets/skills/docx/assets/styles/corporate_styles.xml +284 -0
  99. package/assets/skills/docx/assets/styles/default_styles.xml +449 -0
  100. package/assets/skills/docx/assets/xsd/aesthetic-rules.xsd +470 -0
  101. package/assets/skills/docx/assets/xsd/business-rules.xsd +130 -0
  102. package/assets/skills/docx/assets/xsd/common-types.xsd +159 -0
  103. package/assets/skills/docx/assets/xsd/wml-subset.xsd +589 -0
  104. package/assets/skills/docx/docs/acceptance-checklists/create.md +7 -0
  105. package/assets/skills/docx/docs/acceptance-checklists/edit.md +6 -0
  106. package/assets/skills/docx/docs/acceptance-checklists/layout-repair.md +7 -0
  107. package/assets/skills/docx/docs/acceptance-checklists/template.md +6 -0
  108. package/assets/skills/docx/docs/acceptance.md +139 -0
  109. package/assets/skills/docx/docs/anti-patterns.md +14 -0
  110. package/assets/skills/docx/docs/backends.md +116 -0
  111. package/assets/skills/docx/docs/evidence.md +73 -0
  112. package/assets/skills/docx/docs/failure-taxonomy.md +71 -0
  113. package/assets/skills/docx/docs/index.md +50 -0
  114. package/assets/skills/docx/docs/rendered-delivery.md +125 -0
  115. package/assets/skills/docx/docs/router.md +122 -0
  116. package/assets/skills/docx/docs/tables-and-numbering.md +27 -0
  117. package/assets/skills/docx/docs/task-apply-template.md +141 -0
  118. package/assets/skills/docx/docs/task-compare-two-docx.md +48 -0
  119. package/assets/skills/docx/docs/task-create.md +124 -0
  120. package/assets/skills/docx/docs/task-edit-fill.md +69 -0
  121. package/assets/skills/docx/docs/task-read-content.md +148 -0
  122. package/assets/skills/docx/docs/task-read-rendered.md +78 -0
  123. package/assets/skills/docx/docs/task-read-structure.md +93 -0
  124. package/assets/skills/docx/docs/task-repair-layout.md +70 -0
  125. package/assets/skills/docx/docs/template-dsl.md +32 -0
  126. package/assets/skills/docx/docs/track-changes.md +15 -0
  127. package/assets/skills/docx/docs/xml-patch-dsl.md +33 -0
  128. package/assets/skills/docx/references/cjk_typography.md +357 -0
  129. package/assets/skills/docx/references/cjk_university_template_guide.md +184 -0
  130. package/assets/skills/docx/references/comments_guide.md +191 -0
  131. package/assets/skills/docx/references/design_good_bad_examples.md +829 -0
  132. package/assets/skills/docx/references/design_principles.md +819 -0
  133. package/assets/skills/docx/references/openxml_element_order.md +308 -0
  134. package/assets/skills/docx/references/openxml_encyclopedia_part1.md +4061 -0
  135. package/assets/skills/docx/references/openxml_encyclopedia_part2.md +2820 -0
  136. package/assets/skills/docx/references/openxml_encyclopedia_part3.md +3381 -0
  137. package/assets/skills/docx/references/openxml_namespaces.md +82 -0
  138. package/assets/skills/docx/references/openxml_units.md +72 -0
  139. package/assets/skills/docx/references/sample-patch-plans.json +22 -0
  140. package/assets/skills/docx/references/sample-task-intents.json +5 -0
  141. package/assets/skills/docx/references/sample-template-manifests.json +21 -0
  142. package/assets/skills/docx/references/scenario_a_create.md +284 -0
  143. package/assets/skills/docx/references/scenario_b_edit_content.md +295 -0
  144. package/assets/skills/docx/references/scenario_c_apply_template.md +456 -0
  145. package/assets/skills/docx/references/track_changes_guide.md +200 -0
  146. package/assets/skills/docx/references/troubleshooting.md +506 -0
  147. package/assets/skills/docx/references/typography_guide.md +294 -0
  148. package/assets/skills/docx/references/xsd_validation_guide.md +158 -0
  149. package/assets/skills/docx/scripts/build_patch_plan.py +29 -0
  150. package/assets/skills/docx/scripts/diff_docx_structure.py +61 -0
  151. package/assets/skills/docx/scripts/doc_to_docx.ps1 +85 -0
  152. package/assets/skills/docx/scripts/doc_to_docx.sh +40 -0
  153. package/assets/skills/docx/scripts/docx_preview.ps1 +76 -0
  154. package/assets/skills/docx/scripts/docx_preview.sh +37 -0
  155. package/assets/skills/docx/scripts/docx_to_pdf.py +87 -0
  156. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Cli/AlranAIDocx.Cli.csproj +19 -0
  157. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Cli/Program.cs +18 -0
  158. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/AlranAIDocx.Core.csproj +15 -0
  159. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Commands/AnalyzeCommand.cs +147 -0
  160. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Commands/ApplyTemplateCommand.cs +322 -0
  161. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Commands/CreateCommand.cs +324 -0
  162. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Commands/DiffCommand.cs +155 -0
  163. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Commands/EditContentCommand.cs +487 -0
  164. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Commands/FixOrderCommand.cs +108 -0
  165. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Commands/MergeRunsCommand.cs +122 -0
  166. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Commands/ValidateCommand.cs +107 -0
  167. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/OpenXml/CommentSynchronizer.cs +169 -0
  168. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/OpenXml/ElementOrder.cs +80 -0
  169. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/OpenXml/NamespaceConstants.cs +42 -0
  170. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/OpenXml/RunMerger.cs +81 -0
  171. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/OpenXml/StyleAnalyzer.cs +81 -0
  172. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/OpenXml/TrackChangesHelper.cs +99 -0
  173. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/OpenXml/UnitConverter.cs +23 -0
  174. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Samples/AestheticRecipeSamples.cs +1832 -0
  175. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Samples/AestheticRecipeSamples_Batch1.cs +910 -0
  176. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Samples/AestheticRecipeSamples_Batch2.cs +999 -0
  177. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Samples/AestheticRecipeSamples_Batch3.cs +1048 -0
  178. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Samples/AestheticRecipeSamples_Batch4.cs +1038 -0
  179. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Samples/CharacterFormattingSamples.cs +1020 -0
  180. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Samples/DocumentCreationSamples.cs +1121 -0
  181. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Samples/FieldAndTocSamples.cs +624 -0
  182. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Samples/FootnoteAndCommentSamples.cs +675 -0
  183. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Samples/HeaderFooterSamples.cs +838 -0
  184. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Samples/ImageSamples.cs +917 -0
  185. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Samples/ListAndNumberingSamples.cs +826 -0
  186. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Samples/ParagraphFormattingSamples.cs +1199 -0
  187. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Samples/StyleSystemSamples.cs +1487 -0
  188. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Samples/TableSamples.cs +1163 -0
  189. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Samples/TrackChangesSamples.cs +595 -0
  190. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Typography/CjkHelper.cs +39 -0
  191. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Typography/FontDefaults.cs +24 -0
  192. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Typography/PageSizes.cs +20 -0
  193. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Validation/BusinessRuleValidator.cs +224 -0
  194. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Validation/GateCheckValidator.cs +148 -0
  195. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Validation/ValidationResult.cs +23 -0
  196. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Validation/XsdValidator.cs +69 -0
  197. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.slnx +4 -0
  198. package/assets/skills/docx/scripts/env_check.ps1 +327 -0
  199. package/assets/skills/docx/scripts/env_check.sh +340 -0
  200. package/assets/skills/docx/scripts/extract_docx_text.py +1075 -0
  201. package/assets/skills/docx/scripts/pack_docx.py +31 -0
  202. package/assets/skills/docx/scripts/read_docx_structure.py +1032 -0
  203. package/assets/skills/docx/scripts/render_docx_pages.py +147 -0
  204. package/assets/skills/docx/scripts/rendered_report.py +609 -0
  205. package/assets/skills/docx/scripts/setup.ps1 +542 -0
  206. package/assets/skills/docx/scripts/setup.sh +537 -0
  207. package/assets/skills/docx/scripts/unpack_docx.py +29 -0
  208. package/assets/skills/docx/scripts/validate_template_manifest.py +60 -0
  209. package/assets/skills/docx/scripts/verify_anchor_atomicity.py +87 -0
  210. package/assets/skills/edit-deployed-website/SKILL.md +27 -0
  211. package/assets/skills/init/SKILL.md +135 -0
  212. package/assets/skills/llm-call/SKILL.md +48 -0
  213. package/assets/skills/llm-call/scripts/llm_call.py +458 -0
  214. package/assets/skills/pdf/SKILL.md +280 -0
  215. package/assets/skills/pdf/docs/advanced-reference.md +711 -0
  216. package/assets/skills/pdf/docs/create-guide.md +437 -0
  217. package/assets/skills/pdf/docs/design-guide.md +204 -0
  218. package/assets/skills/pdf/docs/forms-guide.md +462 -0
  219. package/assets/skills/pdf/docs/html-pdf-spec.md +500 -0
  220. package/assets/skills/pdf/docs/latex-academic-thesis-guide.md +233 -0
  221. package/assets/skills/pdf/docs/latex-technical-book-guide.md +112 -0
  222. package/assets/skills/pdf/docs/pitfalls-index.md +792 -0
  223. package/assets/skills/pdf/docs/read-guide.md +358 -0
  224. package/assets/skills/pdf/docs/reformat-guide.md +238 -0
  225. package/assets/skills/pdf/docs/skill-readme-archive.md +151 -0
  226. package/assets/skills/pdf/docs/troubleshooting.md +86 -0
  227. package/assets/skills/pdf/docs/vision-guide.md +188 -0
  228. package/assets/skills/pdf/scripts/__init__.py +0 -0
  229. package/assets/skills/pdf/scripts/_pdf_read_lib.py +284 -0
  230. package/assets/skills/pdf/scripts/fill/__init__.py +0 -0
  231. package/assets/skills/pdf/scripts/fill/acroform_apply.py +153 -0
  232. package/assets/skills/pdf/scripts/fill/overlay_apply.py +109 -0
  233. package/assets/skills/pdf/scripts/lib/__init__.py +0 -0
  234. package/assets/skills/pdf/scripts/lib/acroform_io.py +170 -0
  235. package/assets/skills/pdf/scripts/lib/cli_utils.py +41 -0
  236. package/assets/skills/pdf/scripts/lib/geometry.py +79 -0
  237. package/assets/skills/pdf/scripts/make.sh +388 -0
  238. package/assets/skills/pdf/scripts/merge.py +112 -0
  239. package/assets/skills/pdf/scripts/pdf_inspect/__init__.py +0 -0
  240. package/assets/skills/pdf/scripts/pdf_inspect/acroform_inspect.py +52 -0
  241. package/assets/skills/pdf/scripts/pdf_inspect/acroform_probe.py +57 -0
  242. package/assets/skills/pdf/scripts/pdf_inspect/layout_scan.py +164 -0
  243. package/assets/skills/pdf/scripts/read_pdf_vision.py +473 -0
  244. package/assets/skills/pdf/scripts/reformat_parse.py +181 -0
  245. package/assets/skills/pdf/scripts/render/__init__.py +0 -0
  246. package/assets/skills/pdf/scripts/render/overlay_preview.py +86 -0
  247. package/assets/skills/pdf/scripts/render/page_rasterize.py +85 -0
  248. package/assets/skills/pdf/scripts/render_html.cjs +205 -0
  249. package/assets/skills/pdf/scripts/validate/__init__.py +0 -0
  250. package/assets/skills/pdf/scripts/validate/geometry_lint.py +124 -0
  251. package/assets/skills/pdf/templates/INDEX.md +90 -0
  252. package/assets/skills/pdf/templates/bilingual-menu-premium/README.md +175 -0
  253. package/assets/skills/pdf/templates/bilingual-menu-premium/skeleton.html +343 -0
  254. package/assets/skills/pdf/templates/brand-guide-2page/README.md +140 -0
  255. package/assets/skills/pdf/templates/brand-guide-2page/skeleton.html +264 -0
  256. package/assets/skills/pdf/templates/data-viz-report/README.md +234 -0
  257. package/assets/skills/pdf/templates/data-viz-report/skeleton.html +835 -0
  258. package/assets/skills/pdf/templates/form-fill-acroform/README.md +195 -0
  259. package/assets/skills/pdf/templates/form-fill-acroform/field_values.template.json +118 -0
  260. package/assets/skills/pdf/templates/latex-academic-thesis/README.md +146 -0
  261. package/assets/skills/pdf/templates/latex-academic-thesis/source.tex +334 -0
  262. package/assets/skills/pdf/templates/latex-technical-book/README.md +130 -0
  263. package/assets/skills/pdf/templates/latex-technical-book/README.template-source.md +62 -0
  264. package/assets/skills/pdf/templates/latex-technical-book/source.tex +439 -0
  265. package/assets/skills/pdf/templates/multi-article-aggregator/README.md +148 -0
  266. package/assets/skills/pdf/templates/multi-article-aggregator/pipeline.md +223 -0
  267. package/assets/skills/pdf/templates/multilang-research-report/README.md +136 -0
  268. package/assets/skills/pdf/templates/multilang-research-report/skeleton.html +242 -0
  269. package/assets/skills/pdf/templates/reformat-default/README.md +136 -0
  270. package/assets/skills/pdf/templates/reformat-default/skeleton.html +204 -0
  271. package/assets/skills/pdf/templates/translate-preserve-layout/README.md +136 -0
  272. package/assets/skills/pdf/templates/translate-preserve-layout/skeleton.html +96 -0
  273. package/assets/skills/pdf/templates/translate-preserve-layout/terminology.template.json +66 -0
  274. package/assets/skills/pptx/SKILL.md +283 -0
  275. package/assets/skills/pptx/references/design-system.md +424 -0
  276. package/assets/skills/pptx/references/editing.md +162 -0
  277. package/assets/skills/pptx/references/element-map.md +229 -0
  278. package/assets/skills/pptx/references/pitfalls.md +205 -0
  279. package/assets/skills/pptx/references/pptxgenjs.md +420 -0
  280. package/assets/skills/pptx/references/preview-selection-writeback.md +65 -0
  281. package/assets/skills/pptx/references/python-pptx-recipes.md +63 -0
  282. package/assets/skills/pptx/references/slide-types.md +413 -0
  283. package/assets/skills/pptx/scripts/alran-ppt-map.cjs +280 -0
  284. package/assets/skills/pptx/scripts/audit_pptx.py +708 -0
  285. package/assets/skills/pptx/scripts/extract_comments.py +468 -0
  286. package/assets/skills/pptx/scripts/extract_images.py +226 -0
  287. package/assets/skills/pptx/scripts/extract_pptx.py +285 -0
  288. package/assets/skills/pptx/scripts/pdf2png.swift +203 -0
  289. package/assets/skills/pptx/scripts/pptx-screenshot.sh +105 -0
  290. package/assets/skills/resume-codex/SKILL.md +53 -0
  291. package/assets/skills/resume-codex/scripts/session-reader.mjs +445 -0
  292. package/assets/skills/skill-creator/SKILL.md +188 -0
  293. package/assets/skills/skill-creator/references/anti-patterns.md +149 -0
  294. package/assets/skills/skill-creator/references/commands-macos-linux.md +38 -0
  295. package/assets/skills/skill-creator/references/commands-windows-powershell.md +48 -0
  296. package/assets/skills/skill-creator/references/description-rubric.md +83 -0
  297. package/assets/skills/skill-creator/references/skill-template.md +101 -0
  298. package/assets/skills/skill-creator/references/when-to-bundle-scripts.md +139 -0
  299. package/assets/skills/skill-creator/scripts/lint-skill.js +226 -0
  300. package/assets/skills/skill-refiner/SKILL.md +137 -0
  301. package/assets/skills/visual-page/SKILL.md +194 -0
  302. package/assets/skills/x-link-reader/SKILL.md +108 -0
  303. package/assets/skills/xlsx/SKILL.md +498 -0
  304. package/assets/skills/xlsx/docs/advanced-reference.md +410 -0
  305. package/assets/skills/xlsx/docs/conventions-guide.md +217 -0
  306. package/assets/skills/xlsx/docs/create-edit-guide.md +410 -0
  307. package/assets/skills/xlsx/docs/pitfalls-index.md +759 -0
  308. package/assets/skills/xlsx/docs/raw-xml-escape-hatch.md +201 -0
  309. package/assets/skills/xlsx/docs/recalc-guide.md +295 -0
  310. package/assets/skills/xlsx/scripts/office/helpers/__init__.py +0 -0
  311. package/assets/skills/xlsx/scripts/office/helpers/merge_runs.py +199 -0
  312. package/assets/skills/xlsx/scripts/office/helpers/simplify_redlines.py +197 -0
  313. package/assets/skills/xlsx/scripts/office/pack.py +159 -0
  314. package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-chart.xsd +1499 -0
  315. package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-chartDrawing.xsd +146 -0
  316. package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-diagram.xsd +1085 -0
  317. package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-lockedCanvas.xsd +11 -0
  318. package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-main.xsd +3081 -0
  319. package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-picture.xsd +23 -0
  320. package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-spreadsheetDrawing.xsd +185 -0
  321. package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-wordprocessingDrawing.xsd +287 -0
  322. package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/pml.xsd +1676 -0
  323. package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-additionalCharacteristics.xsd +28 -0
  324. package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-bibliography.xsd +144 -0
  325. package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-commonSimpleTypes.xsd +174 -0
  326. package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-customXmlDataProperties.xsd +25 -0
  327. package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-customXmlSchemaProperties.xsd +18 -0
  328. package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesCustom.xsd +59 -0
  329. package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesExtended.xsd +56 -0
  330. package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesVariantTypes.xsd +195 -0
  331. package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-math.xsd +582 -0
  332. package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-relationshipReference.xsd +25 -0
  333. package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/sml.xsd +4439 -0
  334. package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/vml-main.xsd +570 -0
  335. package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/vml-officeDrawing.xsd +509 -0
  336. package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/vml-presentationDrawing.xsd +12 -0
  337. package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/vml-spreadsheetDrawing.xsd +108 -0
  338. package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/vml-wordprocessingDrawing.xsd +96 -0
  339. package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/wml.xsd +3646 -0
  340. package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/xml.xsd +116 -0
  341. package/assets/skills/xlsx/scripts/office/schemas/ecma/fouth-edition/opc-contentTypes.xsd +42 -0
  342. package/assets/skills/xlsx/scripts/office/schemas/ecma/fouth-edition/opc-coreProperties.xsd +50 -0
  343. package/assets/skills/xlsx/scripts/office/schemas/ecma/fouth-edition/opc-digSig.xsd +49 -0
  344. package/assets/skills/xlsx/scripts/office/schemas/ecma/fouth-edition/opc-relationships.xsd +33 -0
  345. package/assets/skills/xlsx/scripts/office/schemas/mce/mc.xsd +75 -0
  346. package/assets/skills/xlsx/scripts/office/schemas/microsoft/wml-2010.xsd +560 -0
  347. package/assets/skills/xlsx/scripts/office/schemas/microsoft/wml-2012.xsd +67 -0
  348. package/assets/skills/xlsx/scripts/office/schemas/microsoft/wml-2018.xsd +14 -0
  349. package/assets/skills/xlsx/scripts/office/schemas/microsoft/wml-cex-2018.xsd +20 -0
  350. package/assets/skills/xlsx/scripts/office/schemas/microsoft/wml-cid-2016.xsd +13 -0
  351. package/assets/skills/xlsx/scripts/office/schemas/microsoft/wml-sdtdatahash-2020.xsd +4 -0
  352. package/assets/skills/xlsx/scripts/office/schemas/microsoft/wml-symex-2015.xsd +8 -0
  353. package/assets/skills/xlsx/scripts/office/soffice.py +191 -0
  354. package/assets/skills/xlsx/scripts/office/unpack.py +132 -0
  355. package/assets/skills/xlsx/scripts/office/validate.py +117 -0
  356. package/assets/skills/xlsx/scripts/office/validators/__init__.py +15 -0
  357. package/assets/skills/xlsx/scripts/office/validators/base.py +851 -0
  358. package/assets/skills/xlsx/scripts/office/validators/docx.py +446 -0
  359. package/assets/skills/xlsx/scripts/office/validators/pptx.py +275 -0
  360. package/assets/skills/xlsx/scripts/office/validators/redlining.py +247 -0
  361. package/assets/skills/xlsx/scripts/recalc.py +450 -0
  362. package/chunks/account-commands-GW7N3MYC.js +2 -0
  363. package/chunks/anthropic-63VE6MAE.js +2 -0
  364. package/chunks/application-WPPTE6LU.js +2 -0
  365. package/chunks/auth-command-36RMNQZW.js +2 -0
  366. package/chunks/azure-openai-responses-OIP3KVKJ.js +2 -0
  367. package/chunks/chunk-2AYWJZ72.js +2 -0
  368. package/chunks/chunk-2K5H5GA7.js +2 -0
  369. package/chunks/chunk-2TF6JAQM.js +2 -0
  370. package/chunks/chunk-3AODGLMF.js +2 -0
  371. package/chunks/chunk-3GGKARES.js +2 -0
  372. package/chunks/chunk-4CN3IJFH.js +2 -0
  373. package/chunks/chunk-4XP5XUIZ.js +2 -0
  374. package/chunks/chunk-5DQTVSQV.js +131 -0
  375. package/chunks/chunk-5RIMHTEU.js +207 -0
  376. package/chunks/chunk-5Y76VFHY.js +2 -0
  377. package/chunks/chunk-6DOVXX7W.js +2 -0
  378. package/chunks/chunk-6P4UKHGR.js +2 -0
  379. package/chunks/chunk-6PFI65C6.js +5 -0
  380. package/chunks/chunk-6UXSIWCB.js +2 -0
  381. package/chunks/chunk-7XYOYZX2.js +2 -0
  382. package/chunks/chunk-AGUSPIUP.js +2 -0
  383. package/chunks/chunk-BQ3CF3KE.js +2 -0
  384. package/chunks/chunk-C6LAAFG2.js +30 -0
  385. package/chunks/chunk-CUG7F2FN.js +2 -0
  386. package/chunks/chunk-D66ZSHXR.js +2 -0
  387. package/chunks/chunk-D7MGU75P.js +2 -0
  388. package/chunks/chunk-DFMYLGVU.js +249 -0
  389. package/chunks/chunk-EJN3SE5B.js +16 -0
  390. package/chunks/chunk-F46IELF5.js +2 -0
  391. package/chunks/chunk-G5MOGPZ3.js +6711 -0
  392. package/chunks/chunk-GP52JZMY.js +2 -0
  393. package/chunks/chunk-HNWBFJNO.js +2 -0
  394. package/chunks/chunk-IC6A323Q.js +2 -0
  395. package/chunks/chunk-IN2Z5SSJ.js +164 -0
  396. package/chunks/chunk-JSTSFMGK.js +70 -0
  397. package/chunks/chunk-K5DTFR6D.js +29 -0
  398. package/chunks/chunk-LCC45PCZ.js +29 -0
  399. package/chunks/chunk-LU4RPLJ3.js +2 -0
  400. package/chunks/chunk-LZJYNT32.js +2 -0
  401. package/chunks/chunk-MACBL5HF.js +2 -0
  402. package/chunks/chunk-MPQ6G7LH.js +1085 -0
  403. package/chunks/chunk-MUXNNOSQ.js +3 -0
  404. package/chunks/chunk-N5NTXCJI.js +2 -0
  405. package/chunks/chunk-N6W7ZL26.js +2 -0
  406. package/chunks/chunk-NBONSNQZ.js +38 -0
  407. package/chunks/chunk-NMKRNU5O.js +2 -0
  408. package/chunks/chunk-NVPGGFT3.js +2 -0
  409. package/chunks/chunk-NZXJAHTO.js +9 -0
  410. package/chunks/chunk-OTDNOWXG.js +16 -0
  411. package/chunks/chunk-PCL2CVVE.js +2 -0
  412. package/chunks/chunk-PXH4SBCS.js +3 -0
  413. package/chunks/chunk-QKBN5CGI.js +2 -0
  414. package/chunks/chunk-QPGTKSIQ.js +2 -0
  415. package/chunks/chunk-R44C5DM6.js +2 -0
  416. package/chunks/chunk-RLJVY75P.js +28 -0
  417. package/chunks/chunk-RLND4AYL.js +4 -0
  418. package/chunks/chunk-SIOLUFGG.js +2 -0
  419. package/chunks/chunk-TJC4LPRQ.js +2 -0
  420. package/chunks/chunk-U3RMPDXU.js +2 -0
  421. package/chunks/chunk-U4PFHJ7Z.js +27 -0
  422. package/chunks/chunk-UJCAE7SG.js +3 -0
  423. package/chunks/chunk-V2SB4U4D.js +2 -0
  424. package/chunks/chunk-VGKKKM2W.js +6 -0
  425. package/chunks/chunk-VLXX22YO.js +2 -0
  426. package/chunks/chunk-VUISZDXX.js +24 -0
  427. package/chunks/chunk-W5ZOLW7T.js +2 -0
  428. package/chunks/chunk-WHD2XVT2.js +2 -0
  429. package/chunks/chunk-XLVABFJC.js +9 -0
  430. package/chunks/chunk-XQK7JM66.js +2 -0
  431. package/chunks/chunk-XSEU4WQD.js +7 -0
  432. package/chunks/chunk-XVGPB7TW.js +21 -0
  433. package/chunks/chunk-Z5HOCNTZ.js +2 -0
  434. package/chunks/chunk-ZDI22NOK.js +7 -0
  435. package/chunks/chunk-ZQKVUPKA.js +2 -0
  436. package/chunks/clipboard-image-PQPC4EHR.js +2 -0
  437. package/chunks/data-dir-OEPRRIOO.js +2 -0
  438. package/chunks/dist-VKYZJYR6.js +11 -0
  439. package/chunks/dist-WGTMUM3E.js +5 -0
  440. package/chunks/emscripten-module-3WGSFZYF.js +2 -0
  441. package/chunks/emscripten-module-74WUXTHL.js +2 -0
  442. package/chunks/emscripten-module-MCN4Y3N4.js +2 -0
  443. package/chunks/emscripten-module-NEAT5LGD.js +2 -0
  444. package/chunks/ffi-EFLUAAVX.js +2 -0
  445. package/chunks/ffi-JIGPPPF7.js +2 -0
  446. package/chunks/ffi-QKKA5HYI.js +2 -0
  447. package/chunks/ffi-RLX77WFG.js +2 -0
  448. package/chunks/google-RCR46TTQ.js +2 -0
  449. package/chunks/google-vertex-Y26T7YYR.js +2 -0
  450. package/chunks/install-source-63OVVBMK.js +2 -0
  451. package/chunks/launcher-2UG3JPYF.js +63 -0
  452. package/chunks/lifecycle-5IPJRP2V.js +2 -0
  453. package/chunks/main-7SGOQBHZ.js +13 -0
  454. package/chunks/mistral-NEBDKUEI.js +3 -0
  455. package/chunks/module-6F3E5H7Y-FIMLNSCK.js +2 -0
  456. package/chunks/module-asyncify-R6PWJ6ZV-Q2HJ3NOC.js +2 -0
  457. package/chunks/multipart-parser-JVSLI2CL.js +2 -0
  458. package/chunks/network-proxy-AJO7ZW3O.js +2 -0
  459. package/chunks/openai-codex-responses-L2CIGCKO.js +2 -0
  460. package/chunks/openai-completions-C4PHW6MD.js +2 -0
  461. package/chunks/openai-responses-5NVFOW4Y.js +2 -0
  462. package/chunks/openrouter-BKUGQT7Z.js +2 -0
  463. package/chunks/otel-DRJM2PIX.js +2 -0
  464. package/chunks/package-contract-GVXTMJ3N.js +2 -0
  465. package/chunks/pdfjs-2UOWBGC2.js +107 -0
  466. package/chunks/photon_rs-MVWYTYTO.js +3 -0
  467. package/chunks/plugin-command-CIDTOPNB.js +2 -0
  468. package/chunks/provider-command-UZ7KQFAC.js +2 -0
  469. package/chunks/questionnaire-bridge-ISQOCYWY.js +2 -0
  470. package/chunks/run-acp-command-AKDLHKMR.js +59 -0
  471. package/chunks/run-exec-command-UXTPS7LC.js +15 -0
  472. package/chunks/skills-command-57TF53NO.js +2 -0
  473. package/chunks/src-5PSNGHHD.js +2 -0
  474. package/chunks/src-YZ26EVSY.js +2 -0
  475. package/chunks/telemetry-3NXMCOVD.js +2 -0
  476. package/chunks/telemetry-command-CMDERYNN.js +5 -0
  477. package/chunks/tools-CRJR35HS.js +2 -0
  478. package/chunks/undici-O4OQVZ6I.js +2 -0
  479. package/chunks/update-ACFAGV6F.js +14 -0
  480. package/chunks/update-hint-ED7O67WU.js +3 -0
  481. package/chunks/wechat-onboard-UWXQW2HT.js +2 -0
  482. package/cli.js +4 -0
  483. package/configs/data-minimal.yaml +50 -0
  484. package/embedded/alran-tools/cli.mjs +4957 -0
  485. package/embedded/alran-tools/manifest.json +25 -0
  486. package/emscripten-module.wasm +0 -0
  487. package/image-preview-worker.js +2 -0
  488. package/internal-bin/alran-tools +9 -0
  489. package/internal-bin/alran-tools.cmd +8 -0
  490. package/matrix-mcp-stdio.js +4 -0
  491. package/native/darwin/prebuilds/darwin-arm64/darwin-modifiers.node +0 -0
  492. package/native/darwin/prebuilds/darwin-x64/darwin-modifiers.node +0 -0
  493. package/native/win32/prebuilds/win32-arm64/win32-console-mode.node +0 -0
  494. package/native/win32/prebuilds/win32-x64/win32-console-mode.node +0 -0
  495. package/package.json +38 -4
  496. package/photon_rs_bg.wasm +0 -0
  497. package/quickjs-worker.js +152 -0
  498. package/vendor/java-proxy-agent/build.ts +97 -0
  499. package/vendor/java-proxy-agent/srt-proxy-agent.jar +0 -0
  500. package/vendor/seccomp/arm64/apply-seccomp +0 -0
  501. package/vendor/seccomp/build.ts +74 -0
  502. package/vendor/seccomp/x64/apply-seccomp +0 -0
  503. package/vendor/srt-win/arm64/srt-win.exe +0 -0
  504. package/vendor/srt-win/build.ts +40 -0
  505. package/vendor/srt-win/x64/srt-win.exe +0 -0
@@ -0,0 +1,30 @@
1
+ import { createRequire as __alran_cR } from "module"; import { basename as __alran_basename, dirname as __alran_dirname, join as __alran_join } from "path"; import { fileURLToPath as __alran_fileURLToPath, pathToFileURL as __alran_pathToFileURL } from "url"; const __alran_tuiCurrentModuleDir = __alran_dirname(__alran_fileURLToPath(import.meta.url)); const __alran_tuiPackageRoot = __alran_basename(__alran_tuiCurrentModuleDir) === "chunks" ? __alran_dirname(__alran_tuiCurrentModuleDir) : __alran_tuiCurrentModuleDir; const __alran_tuiPackageEntryUrl = __alran_pathToFileURL(__alran_join(__alran_tuiPackageRoot, "cli.js")).href; const require = __alran_cR(__alran_tuiPackageEntryUrl); const __dirname = __alran_tuiPackageRoot;
2
+ import{a as Ka}from"./chunk-UJCAE7SG.js";import{l as Ja}from"./chunk-VLXX22YO.js";import{a as vt}from"./chunk-7XYOYZX2.js";import{a as an}from"./chunk-XSEU4WQD.js";import{a as z,c as F,e as $a}from"./chunk-XQK7JM66.js";var Ya=F((SS,Wa)=>{function xe(t,e){if(typeof e==="boolean"){e={forever:e}}this._originalTimeouts=JSON.parse(JSON.stringify(t));this._timeouts=t;this._options=e||{};this._maxRetryTime=e&&e.maxRetryTime||Infinity;this._fn=null;this._errors=[];this._attempts=1;this._operationTimeout=null;this._operationTimeoutCb=null;this._timeout=null;this._operationStart=null;this._timer=null;if(this._options.forever){this._cachedTimeouts=this._timeouts.slice(0)}}Wa.exports=xe;xe.prototype.reset=function(){this._attempts=1;this._timeouts=this._originalTimeouts.slice(0)};xe.prototype.stop=function(){if(this._timeout){clearTimeout(this._timeout)}if(this._timer){clearTimeout(this._timer)}this._timeouts=[];this._cachedTimeouts=null};xe.prototype.retry=function(t){if(this._timeout){clearTimeout(this._timeout)}if(!t){return false}var e=new Date().getTime();if(t&&e-this._operationStart>=this._maxRetryTime){this._errors.push(t);this._errors.unshift(new Error("RetryOperation timeout occurred"));return false}this._errors.push(t);var n=this._timeouts.shift();if(n===void 0){if(this._cachedTimeouts){this._errors.splice(0,this._errors.length-1);n=this._cachedTimeouts.slice(-1)}else{return false}}var i=this;this._timer=setTimeout(function(){i._attempts++;if(i._operationTimeoutCb){i._timeout=setTimeout(function(){i._operationTimeoutCb(i._attempts)},i._operationTimeout);if(i._options.unref){i._timeout.unref()}}i._fn(i._attempts)},n);if(this._options.unref){this._timer.unref()}return true};xe.prototype.attempt=function(t,e){this._fn=t;if(e){if(e.timeout){this._operationTimeout=e.timeout}if(e.cb){this._operationTimeoutCb=e.cb}}var n=this;if(this._operationTimeoutCb){this._timeout=setTimeout(function(){n._operationTimeoutCb()},n._operationTimeout)}this._operationStart=new Date().getTime();this._fn(this._attempts)};xe.prototype.try=function(t){console.log("Using RetryOperation.try() is deprecated");this.attempt(t)};xe.prototype.start=function(t){console.log("Using RetryOperation.start() is deprecated");this.attempt(t)};xe.prototype.start=xe.prototype.try;xe.prototype.errors=function(){return this._errors};xe.prototype.attempts=function(){return this._attempts};xe.prototype.mainError=function(){if(this._errors.length===0){return null}var t={};var e=null;var n=0;for(var i=0;i<this._errors.length;i++){var r=this._errors[i];var o=r.message;var l=(t[o]||0)+1;t[o]=l;if(l>=n){e=r;n=l}}return e}});var za=F(St=>{var ep=Ya();St.operation=function(t){var e=St.timeouts(t);return new ep(e,{forever:t&&(t.forever||t.retries===Infinity),unref:t&&t.unref,maxRetryTime:t&&t.maxRetryTime})};St.timeouts=function(t){if(t instanceof Array){return[].concat(t)}var e={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:Infinity,randomize:false};for(var n in t){e[n]=t[n]}if(e.minTimeout>e.maxTimeout){throw new Error("minTimeout is greater than maxTimeout")}var i=[];for(var r=0;r<e.retries;r++){i.push(this.createTimeout(r,e))}if(t&&t.forever&&!i.length){i.push(this.createTimeout(r,e))}i.sort(function(o,l){return o-l});return i};St.createTimeout=function(t,e){var n=e.randomize?Math.random()+1:1;var i=Math.round(n*Math.max(e.minTimeout,1)*Math.pow(e.factor,t));i=Math.min(i,e.maxTimeout);return i};St.wrap=function(t,e,n){if(e instanceof Array){n=e;e=null}if(!n){n=[];for(var i in t){if(typeof t[i]==="function"){n.push(i)}}}for(var r=0;r<n.length;r++){var o=n[r];var l=t[o];t[o]=function u(c){var d=St.operation(e);var f=Array.prototype.slice.call(arguments,1);var p=f.pop();f.push(function(h){if(d.retry(h)){return}if(h){arguments[0]=d.mainError()}p.apply(this,arguments)});d.attempt(function(){c.apply(t,f)})}.bind(t,l);t[o].options=e}}});var Qa=F((wS,Xa)=>{Xa.exports=za()});var ja=F((RS,xn)=>{"use strict";var tp=Qa();var np=["Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed"];var kn=class extends Error{constructor(e){super();if(e instanceof Error){this.originalError=e;({message:e}=e)}else{this.originalError=new Error(e);this.originalError.stack=this.stack}this.name="AbortError";this.message=e}};var ip=(t,e,n)=>{const i=n.retries-(e-1);t.attemptNumber=e;t.retriesLeft=i;return t};var rp=t=>np.includes(t);var Za=(t,e)=>new Promise((n,i)=>{e={onFailedAttempt:()=>{},retries:10,...e};const r=tp.operation(e);r.attempt(async o=>{try{n(await t(o))}catch(l){if(!(l instanceof Error)){i(new TypeError(`Non-error was thrown: "${l}". You should only throw errors.`));return}if(l instanceof kn){r.stop();i(l.originalError)}else if(l instanceof TypeError&&!rp(l.message)){r.stop();i(l)}else{ip(l,o,e);try{await e.onFailedAttempt(l)}catch(u){i(u);return}if(!r.retry(l)){i(r.mainError())}}}})});xn.exports=Za;xn.exports.default=Za;xn.exports.AbortError=kn});var vr=F((PS,al)=>{"use strict";var Dn=Object.prototype.hasOwnProperty;var sl=Object.prototype.toString;var el=Object.defineProperty;var tl=Object.getOwnPropertyDescriptor;var nl=function t(e){if(typeof Array.isArray==="function"){return Array.isArray(e)}return sl.call(e)==="[object Array]"};var il=function t(e){if(!e||sl.call(e)!=="[object Object]"){return false}var n=Dn.call(e,"constructor");var i=e.constructor&&e.constructor.prototype&&Dn.call(e.constructor.prototype,"isPrototypeOf");if(e.constructor&&!n&&!i){return false}var r;for(r in e){}return typeof r==="undefined"||Dn.call(e,r)};var rl=function t(e,n){if(el&&n.name==="__proto__"){el(e,n.name,{enumerable:true,configurable:true,value:n.newValue,writable:true})}else{e[n.name]=n.newValue}};var ol=function t(e,n){if(n==="__proto__"){if(!Dn.call(e,n)){return void 0}else if(tl){return tl(e,n).value}}return e[n]};al.exports=function t(){var e,n,i,r,o,l;var u=arguments[0];var c=1;var d=arguments.length;var f=false;if(typeof u==="boolean"){f=u;u=arguments[1]||{};c=2}if(u==null||typeof u!=="object"&&typeof u!=="function"){u={}}for(;c<d;++c){e=arguments[c];if(e!=null){for(n in e){i=ol(u,n);r=ol(e,n);if(u!==r){if(f&&r&&(il(r)||(o=nl(r)))){if(o){o=false;l=i&&nl(i)?i:[]}else{l=i&&il(i)?i:{}}rl(u,{name:n,newValue:t(f,l,r)})}else if(typeof r!=="undefined"){rl(u,{name:n,newValue:r})}}}}}return u}});var ll=F((NS,op)=>{op.exports={name:"gaxios",version:"7.3.1",description:"A simple common HTTP client specifically for Google APIs and services.",main:"build/cjs/src/index.js",types:"build/cjs/src/index.d.ts",files:["build/"],exports:{".":{import:{types:"./build/esm/src/index.d.ts",default:"./build/esm/src/index.js"},require:{types:"./build/cjs/src/index.d.ts",default:"./build/cjs/src/index.js"}}},scripts:{lint:"gts check --no-inline-config",test:"c8 mocha build/esm/test","presystem-test":"npm run compile","system-test":"mocha build/esm/system-test --timeout 80000",compile:"tsc -b ./tsconfig.json ./tsconfig.cjs.json && node utils/enable-esm.mjs",fix:"gts fix",prepare:"npm run compile",pretest:"npm run compile",webpack:"webpack","prebrowser-test":"npm run compile","browser-test":"node build/browser-test/browser-test-runner.js",docs:"jsdoc -c .jsdoc.js","samples-test":"cd samples/ && npm link ../ && npm test && cd ../",prelint:"cd samples; npm link ../; npm install",clean:"gts clean"},repository:{type:"git",directory:"core/packages/gaxios",url:"https://github.com/googleapis/google-cloud-node.git"},keywords:["google"],engines:{node:">=18"},author:"Google, LLC",license:"Apache-2.0",devDependencies:{"@babel/plugin-proposal-private-methods":"^7.18.6","@types/cors":"^2.8.6","@types/express":"^5.0.0","@types/extend":"^3.0.1","@types/mocha":"^10.0.10","@types/multiparty":"4.2.1","@types/mv":"^2.1.0","@types/ncp":"^2.0.8","@types/node":"^24.0.0","@types/sinon":"^21.0.0","@types/tmp":"^0.2.6",assert:"^2.0.0",browserify:"^17.0.0",c8:"^10.1.3",cors:"^2.8.5",express:"^5.0.0",gts:"^6.0.2","is-docker":"^3.0.0",jsdoc:"^4.0.4","jsdoc-fresh":"^5.0.0","jsdoc-region-tag":"^4.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-remap-coverage":"^0.1.5","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.0",mocha:"^11.1.0",multiparty:"^4.2.1",mv:"^2.1.1",ncp:"^2.0.0",nock:"14.0.5","null-loader":"^4.0.1","pack-n-play":"^4.0.0",puppeteer:"^24.0.0",sinon:"21.0.3","stream-browserify":"^3.0.0",tmp:"0.2.7","ts-loader":"^9.5.2",typescript:"5.8.3","undici-types":"^7.24.1",webpack:"^5.97.1","webpack-cli":"^6.0.1"},dependencies:{extend:"^3.0.2","https-proxy-agent":"^7.0.1","node-fetch":"^3.3.2"},homepage:"https://github.com/googleapis/google-cloud-node/tree/main/core/packages/gaxios"}});var cl=F((MS,ul)=>{"use strict";var sp=ll();ul.exports={pkg:sp}});var wr=F(De=>{"use strict";var fl=De&&De.__importDefault||function(t){return t&&t.__esModule?t:{"default":t}};Object.defineProperty(De,"__esModule",{value:true});De.GaxiosError=De.GAXIOS_ERROR_SYMBOL=void 0;De.defaultErrorRedactor=pl;var dl=fl(vr());var ap=fl(cl());var Sr=ap.default.pkg;De.GAXIOS_ERROR_SYMBOL=Symbol.for(`${Sr.name}-gaxios-error`);var Ir=class t extends Error{config;response;code;status;error;[De.GAXIOS_ERROR_SYMBOL]=Sr.version;static[Symbol.hasInstance](e){if(e&&typeof e==="object"&&De.GAXIOS_ERROR_SYMBOL in e&&e[De.GAXIOS_ERROR_SYMBOL]===Sr.version){return true}return Function.prototype[Symbol.hasInstance].call(t,e)}constructor(e,n,i,r){super(e,{cause:r});this.config=n;this.response=i;this.error=r instanceof Error?r:void 0;this.config=(0,dl.default)(true,{},n);if(this.response){this.response.config=(0,dl.default)(true,{},this.response.config)}if(this.response){try{this.response.data=lp(this.config.responseType,this.response?.bodyUsed?this.response?.data:void 0)}catch{}this.status=this.response.status}if(r instanceof DOMException){this.code=r.name}else if(r&&typeof r==="object"&&"code"in r&&(typeof r.code==="string"||typeof r.code==="number")){this.code=r.code}}static extractAPIErrorFromResponse(e,n="The request failed"){let i=n;if(typeof e.data==="string"){i=e.data}if(e.data&&typeof e.data==="object"&&"error"in e.data&&e.data.error&&!e.ok){if(typeof e.data.error==="string"){return{message:e.data.error,code:e.status,status:e.statusText}}if(typeof e.data.error==="object"){i="message"in e.data.error&&typeof e.data.error.message==="string"?e.data.error.message:i;const r="status"in e.data.error&&typeof e.data.error.status==="string"?e.data.error.status:e.statusText;const o="code"in e.data.error&&typeof e.data.error.code==="number"?e.data.error.code:e.status;if("errors"in e.data.error&&Array.isArray(e.data.error.errors)){const l=[];for(const u of e.data.error.errors){if(typeof u==="object"&&"message"in u&&typeof u.message==="string"){l.push(u.message)}}return Object.assign({message:l.join("\n")||i,code:o,status:r},e.data.error)}return Object.assign({message:i,code:o,status:r},e.data.error)}}return{message:i,code:e.status,status:e.statusText}}};De.GaxiosError=Ir;function lp(t,e){switch(t){case"stream":return e;case"json":return JSON.parse(JSON.stringify(e));case"arraybuffer":return JSON.parse(Buffer.from(e).toString("utf8"));case"blob":return JSON.parse(e.text());default:return e}}function pl(t){const e="<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.";function n(o){if(!o)return;o.forEach((l,u)=>{if(/^authentication$/i.test(u)||/^authorization$/i.test(u)||/secret/i.test(u))o.set(u,e)})}function i(o,l){if(typeof o==="object"&&o!==null&&typeof o[l]==="string"){const u=o[l];if(/grant_type=/i.test(u)||/assertion=/i.test(u)||/secret/i.test(u)){o[l]=e}}}function r(o){if(!o||typeof o!=="object"){return}else if(o instanceof FormData||o instanceof URLSearchParams||"forEach"in o&&"set"in o){o.forEach((l,u)=>{if(["grant_type","assertion"].includes(u)||/secret/.test(u)){o.set(u,e)}})}else{if("grant_type"in o){o["grant_type"]=e}if("assertion"in o){o["assertion"]=e}if("client_secret"in o){o["client_secret"]=e}}}if(t.config){n(t.config.headers);i(t.config,"data");r(t.config.data);i(t.config,"body");r(t.config.body);if(t.config.url.searchParams.has("token")){t.config.url.searchParams.set("token",e)}if(t.config.url.searchParams.has("client_secret")){t.config.url.searchParams.set("client_secret",e)}}if(t.response){pl({config:t.response.config});n(t.response.headers);if(t.response.bodyUsed){i(t.response,"data");r(t.response.data)}}return t}});var gl=F(Rr=>{"use strict";Object.defineProperty(Rr,"__esModule",{value:true});Rr.getRetryConfig=up;async function up(t){let e=hl(t);if(!t||!t.config||!e&&!t.config.retry){return{shouldRetry:false}}e=e||{};e.currentRetryAttempt=e.currentRetryAttempt||0;e.retry=e.retry===void 0||e.retry===null?3:e.retry;e.httpMethodsToRetry=e.httpMethodsToRetry||["GET","HEAD","PUT","OPTIONS","DELETE"];e.noResponseRetries=e.noResponseRetries===void 0||e.noResponseRetries===null?2:e.noResponseRetries;e.retryDelayMultiplier=e.retryDelayMultiplier?e.retryDelayMultiplier:2;e.timeOfFirstRequest=e.timeOfFirstRequest?e.timeOfFirstRequest:Date.now();e.totalTimeout=e.totalTimeout?e.totalTimeout:Number.MAX_SAFE_INTEGER;e.maxRetryDelay=e.maxRetryDelay?e.maxRetryDelay:Number.MAX_SAFE_INTEGER;const n=[[100,199],[408,408],[429,429],[500,599]];e.statusCodesToRetry=e.statusCodesToRetry||n;t.config.retryConfig=e;const i=e.shouldRetry||cp;if(!await i(t)){return{shouldRetry:false,config:t.config}}const r=dp(e);t.config.retryConfig.currentRetryAttempt+=1;const o=e.retryBackoff?e.retryBackoff(t,r):new Promise(l=>{setTimeout(l,r)});if(e.onRetryAttempt){await e.onRetryAttempt(t)}await o;return{shouldRetry:true,config:t.config}}function cp(t){const e=hl(t);if(t.config.signal?.aborted&&t.code!=="TimeoutError"||t.code==="AbortError"){return false}if(!e||e.retry===0){return false}if(!t.response&&(e.currentRetryAttempt||0)>=e.noResponseRetries){return false}if(!e.httpMethodsToRetry||!e.httpMethodsToRetry.includes(t.config.method?.toUpperCase()||"GET")){return false}if(t.response&&t.response.status){let n=false;for(const[i,r]of e.statusCodesToRetry){const o=t.response.status;if(o>=i&&o<=r){n=true;break}}if(!n){return false}}e.currentRetryAttempt=e.currentRetryAttempt||0;if(e.currentRetryAttempt>=e.retry){return false}return true}function hl(t){if(t&&t.config&&t.config.retryConfig){return t.config.retryConfig}return}function dp(t){const e=t.currentRetryAttempt?0:t.retryDelay??100;const n=e+(Math.pow(t.retryDelayMultiplier,t.currentRetryAttempt)-1)/2*1e3;const i=t.totalTimeout-(Date.now()-t.timeOfFirstRequest);return Math.min(n,i,t.maxRetryDelay)}});var Nr=F(Un=>{"use strict";Object.defineProperty(Un,"__esModule",{value:true});Un.GaxiosInterceptorManager=void 0;var Pr=class extends Set{};Un.GaxiosInterceptorManager=Pr});var El=F(Dt=>{"use strict";var fp=Dt&&Dt.__importDefault||function(t){return t&&t.__esModule?t:{"default":t}};var xt;Object.defineProperty(Dt,"__esModule",{value:true});Dt.Gaxios=void 0;var pp=fp(vr());var hp=z("https");var It=wr();var gp=gl();var ml=z("stream");var yl=Nr();var mp=async()=>globalThis.crypto?.randomUUID()||(await import("crypto")).randomUUID();var yp=204;var Ln=class{agentCache=new Map;defaults;interceptors;constructor(e){this.defaults=e||{};this.interceptors={request:new yl.GaxiosInterceptorManager,response:new yl.GaxiosInterceptorManager}}fetch(...e){const n=e[0];const i=e[1];let r=void 0;const o=new Headers;if(typeof n==="string"){r=new URL(n)}else if(n instanceof URL){r=n}else if(n&&n.url){r=new URL(n.url)}if(n&&typeof n==="object"&&"headers"in n){xt.mergeHeaders(o,n.headers)}if(i){xt.mergeHeaders(o,new Headers(i.headers))}if(typeof n==="object"&&!(n instanceof URL)){return this.request({...i,...n,headers:o,url:r})}else{return this.request({...i,headers:o,url:r})}}async request(e={}){let n=await this.#i(e);n=await this.#t(n);return this.#n(this._request(n))}async _defaultAdapter(e){const n=e.fetchImplementation||this.defaults.fetchImplementation||await xt.#l();const i={...e};delete i.data;const r=await n(e.url,i);const o=await this.getResponseData(e,r);if(!Object.getOwnPropertyDescriptor(r,"data")?.configurable){Object.defineProperties(r,{data:{configurable:true,writable:true,enumerable:true,value:o}})}return Object.assign(r,{config:e,data:o})}async _request(e){try{let n;if(e.adapter){n=await e.adapter(e,this._defaultAdapter.bind(this))}else{n=await this._defaultAdapter(e)}if(!e.validateStatus(n.status)){if(e.responseType==="stream"){const r=[];for await(const o of n.data){r.push(o)}n.data=Buffer.concat(r.map(o=>typeof o==="string"?Buffer.from(o):o)).toString("utf8")}const i=It.GaxiosError.extractAPIErrorFromResponse(n,`Request failed with status code ${n.status}`);throw new It.GaxiosError(i?.message,e,n,i)}return n}catch(n){let i;if(n instanceof It.GaxiosError){i=n}else if(n instanceof Error){i=new It.GaxiosError(n.message,e,void 0,n)}else{i=new It.GaxiosError("Unexpected Gaxios Error",e,void 0,n)}const{shouldRetry:r,config:o}=await(0,gp.getRetryConfig)(i);if(r&&o){i.config.retryConfig.currentRetryAttempt=o.retryConfig.currentRetryAttempt;e.retryConfig=i.config?.retryConfig;this.#r(e);return this._request(e)}if(e.errorRedactor){e.errorRedactor(i)}throw i}}async getResponseData(e,n){if(n.status===yp){return""}if(e.maxContentLength&&n.headers.has("content-length")&&e.maxContentLength<Number.parseInt(n.headers?.get("content-length")||"")){throw new It.GaxiosError("Response's `Content-Length` is over the limit.",e,Object.assign(n,{config:e}))}switch(e.responseType){case"stream":return n.body;case"json":{const i=await n.text();try{return JSON.parse(i)}catch{return i}}case"arraybuffer":return n.arrayBuffer();case"blob":return n.blob();case"text":return n.text();default:return this.getResponseDataFromContentType(n)}}#e(e,n=[]){const i=new URL(e);const r=[...n];const o=(process.env.NO_PROXY??process.env.no_proxy)?.split(",")||[];for(const l of o){r.push(l.trim())}for(const l of r){if(l instanceof RegExp){if(l.test(i.toString())){return false}}else if(l instanceof URL){if(l.origin===i.origin){return false}}else if(l.startsWith("*.")||l.startsWith(".")){const u=l.replace(/^\*\./,".");if(i.hostname.endsWith(u)){return false}}else if(l===i.origin||l===i.hostname||l===i.href){return false}}return true}async#t(e){let n=Promise.resolve(e);for(const i of this.interceptors.request.values()){if(i){n=n.then(i.resolved,i.rejected)}}return n}async#n(e){let n=Promise.resolve(e);for(const i of this.interceptors.response.values()){if(i){n=n.then(i.resolved,i.rejected)}}return n}async#i(e){const n=new Headers(this.defaults.headers);xt.mergeHeaders(n,e.headers);const i=(0,pp.default)(true,{},this.defaults,e);if(!i.url){throw new Error("URL is required.")}if(i.baseURL){i.url=new URL(i.url,i.baseURL)}i.url=new URL(i.url);if(i.params){if(i.paramsSerializer){let l=i.paramsSerializer(i.params);if(l.startsWith("?")){l=l.slice(1)}const u=i.url.toString().includes("?")?"&":"?";i.url=i.url+u+l}else{const l=i.url instanceof URL?i.url:new URL(i.url);for(const[u,c]of new URLSearchParams(i.params)){l.searchParams.append(u,c)}i.url=l}}if(typeof e.maxContentLength==="number"){i.size=e.maxContentLength}if(typeof e.maxRedirects==="number"){i.follow=e.maxRedirects}const r=typeof i.data==="string"||i.data instanceof ArrayBuffer||i.data instanceof Blob||globalThis.File&&i.data instanceof File||i.data instanceof FormData||i.data instanceof ml.Readable||i.data instanceof ReadableStream||i.data instanceof String||i.data instanceof URLSearchParams||ArrayBuffer.isView(i.data)||["Blob","File","FormData"].includes(i.data?.constructor?.name||"");if(i.multipart?.length){const l=await mp();n.set("content-type",`multipart/related; boundary=${l}`);i.body=ml.Readable.from(this.getMultipartRequest(i.multipart,l))}else if(r){i.body=i.data}else if(typeof i.data==="object"){if(n.get("Content-Type")==="application/x-www-form-urlencoded"){i.body=i.paramsSerializer?i.paramsSerializer(i.data):new URLSearchParams(i.data)}else{if(!n.has("content-type")){n.set("content-type","application/json")}i.body=JSON.stringify(i.data)}}else if(i.data){i.body=i.data}i.validateStatus=i.validateStatus||this.validateStatus;i.responseType=i.responseType||"unknown";if(!n.has("accept")&&i.responseType==="json"){n.set("accept","application/json")}const o=i.proxy||process?.env?.HTTPS_PROXY||process?.env?.https_proxy||process?.env?.HTTP_PROXY||process?.env?.http_proxy;if(i.agent){}else if(o&&this.#e(i.url,i.noProxy)){const l=await xt.#a();if(this.agentCache.has(o)){i.agent=this.agentCache.get(o)}else{i.agent=new l(o,{cert:i.cert,key:i.key});this.agentCache.set(o,i.agent)}}else if(i.cert&&i.key){if(this.agentCache.has(i.key)){i.agent=this.agentCache.get(i.key)}else{i.agent=new hp.Agent({cert:i.cert,key:i.key});this.agentCache.set(i.key,i.agent)}}if(typeof i.errorRedactor!=="function"&&i.errorRedactor!==false){i.errorRedactor=It.defaultErrorRedactor}if(i.body&&!("duplex"in i)){i.duplex="half"}this.#r(i);return Object.assign(i,{headers:n,url:i.url instanceof URL?i.url:new URL(i.url)})}#r(e){if(e.timeout){const n=AbortSignal.timeout(e.timeout);if(e.signal&&!e.signal.aborted){e.signal=AbortSignal.any([e.signal,n])}else{e.signal=n}}}validateStatus(e){return e>=200&&e<300}async getResponseDataFromContentType(e){let n=e.headers.get("Content-Type");if(n===null){return e.text()}n=n.toLowerCase();if(n.includes("application/json")){let i=await e.text();try{i=JSON.parse(i)}catch{}return i}else if(n.match(/^text\//)){return e.text()}else{return e.blob()}}async*getMultipartRequest(e,n){const i=`--${n}--`;for(const r of e){const o=r.headers.get("Content-Type")||"application/octet-stream";const l=`--${n}\r
3
+ Content-Type: ${o}\r
4
+ \r
5
+ `;yield l;if(typeof r.content==="string"){yield r.content}else{yield*r.content}yield"\r\n"}yield i}static#o;static#s;static async#a(){this.#o||=(await import("./dist-WGTMUM3E.js")).HttpsProxyAgent;return this.#o}static async#l(){const e=typeof window!=="undefined"&&!!window;this.#s||=e?window.fetch:(await import("./src-YZ26EVSY.js")).default;return this.#s}static mergeHeaders(e,...n){e=e instanceof Headers?e:new Headers(e);for(const i of n){const r=i instanceof Headers?i:new Headers(i);r.forEach((o,l)=>{l==="set-cookie"?e.append(l,o):e.set(l,o)})}return e}};Dt.Gaxios=Ln;xt=Ln});var ge=F(_e=>{"use strict";var Ep=_e&&_e.__createBinding||(Object.create?(function(t,e,n,i){if(i===void 0)i=n;var r=Object.getOwnPropertyDescriptor(e,n);if(!r||("get"in r?!e.__esModule:r.writable||r.configurable)){r={enumerable:true,get:function(){return e[n]}}}Object.defineProperty(t,i,r)}):(function(t,e,n,i){if(i===void 0)i=n;t[i]=e[n]}));var _p=_e&&_e.__exportStar||function(t,e){for(var n in t)if(n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n))Ep(e,t,n)};Object.defineProperty(_e,"__esModule",{value:true});_e.instance=_e.Gaxios=_e.GaxiosError=void 0;_e.request=Ap;var _l=El();Object.defineProperty(_e,"Gaxios",{enumerable:true,get:function(){return _l.Gaxios}});var Tp=wr();Object.defineProperty(_e,"GaxiosError",{enumerable:true,get:function(){return Tp.GaxiosError}});_p(Nr(),_e);_e.instance=new _l.Gaxios;async function Ap(t){return _e.instance.request(t)}});var Mr=F((Tl,Gn)=>{(function(t){"use strict";var e,n=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,i=Math.ceil,r=Math.floor,o="[BigNumber Error] ",l=o+"Number primitive has more than 15 significant digits: ",u=1e14,c=14,d=9007199254740991,f=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],p=1e7,h=1e9;function m(L){var R,q,V,k=b.prototype={constructor:b,toString:null,valueOf:null},$=new b(1),Y=20,Q=4,oe=-7,ee=21,re=-1e7,le=1e7,Se=false,Ie=1,ce=0,At={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},Ct="0123456789abcdefghijklmnopqrstuvwxyz",Er=true;function b(g,y){var E,N,S,w,x,C,I,M,P=this;if(!(P instanceof b))return new b(g,y);if(y==null){if(g&&g._isBigNumber===true){P.s=g.s;if(!g.c||g.e>le){P.c=P.e=null}else if(g.e<re){P.c=[P.e=0]}else{P.e=g.e;P.c=g.c.slice()}return}if((C=typeof g=="number")&&g*0==0){P.s=1/g<0?(g=-g,-1):1;if(g===~~g){for(w=0,x=g;x>=10;x/=10,w++);if(w>le){P.c=P.e=null}else{P.e=w;P.c=[g]}return}M=String(g)}else{if(!n.test(M=String(g)))return V(P,M,C);P.s=M.charCodeAt(0)==45?(M=M.slice(1),-1):1}if((w=M.indexOf("."))>-1)M=M.replace(".","");if((x=M.search(/e/i))>0){if(w<0)w=x;w+=+M.slice(x+1);M=M.substring(0,x)}else if(w<0){w=M.length}}else{v(y,2,Ct.length,"Base");if(y==10&&Er){P=new b(g);return Me(P,Y+P.e+1,Q)}M=String(g);if(C=typeof g=="number"){if(g*0!=0)return V(P,M,C,y);P.s=1/g<0?(M=M.slice(1),-1):1;if(b.DEBUG&&M.replace(/^0\.0*|\./,"").length>15){throw Error(l+g)}}else{P.s=M.charCodeAt(0)===45?(M=M.slice(1),-1):1}E=Ct.slice(0,y);w=x=0;for(I=M.length;x<I;x++){if(E.indexOf(N=M.charAt(x))<0){if(N=="."){if(x>w){w=I;continue}}else if(!S){if(M==M.toUpperCase()&&(M=M.toLowerCase())||M==M.toLowerCase()&&(M=M.toUpperCase())){S=true;x=-1;w=0;continue}}return V(P,String(g),C,y)}}C=false;M=q(M,y,10,P.s);if((w=M.indexOf("."))>-1)M=M.replace(".","");else w=M.length}for(x=0;M.charCodeAt(x)===48;x++);for(I=M.length;M.charCodeAt(--I)===48;);if(M=M.slice(x,++I)){I-=x;if(C&&b.DEBUG&&I>15&&(g>d||g!==r(g))){throw Error(l+P.s*g)}if((w=w-x-1)>le){P.c=P.e=null}else if(w<re){P.c=[P.e=0]}else{P.e=w;P.c=[];x=(w+1)%c;if(w<0)x+=c;if(x<I){if(x)P.c.push(+M.slice(0,x));for(I-=c;x<I;){P.c.push(+M.slice(x,x+=c))}x=c-(M=M.slice(x)).length}else{x-=I}for(;x--;M+="0");P.c.push(+M)}}else{P.c=[P.e=0]}}b.clone=m;b.ROUND_UP=0;b.ROUND_DOWN=1;b.ROUND_CEIL=2;b.ROUND_FLOOR=3;b.ROUND_HALF_UP=4;b.ROUND_HALF_DOWN=5;b.ROUND_HALF_EVEN=6;b.ROUND_HALF_CEIL=7;b.ROUND_HALF_FLOOR=8;b.EUCLID=9;b.config=b.set=function(g){var y,E;if(g!=null){if(typeof g=="object"){if(g.hasOwnProperty(y="DECIMAL_PLACES")){E=g[y];v(E,0,h,y);Y=E}if(g.hasOwnProperty(y="ROUNDING_MODE")){E=g[y];v(E,0,8,y);Q=E}if(g.hasOwnProperty(y="EXPONENTIAL_AT")){E=g[y];if(E&&E.pop){v(E[0],-h,0,y);v(E[1],0,h,y);oe=E[0];ee=E[1]}else{v(E,-h,h,y);oe=-(ee=E<0?-E:E)}}if(g.hasOwnProperty(y="RANGE")){E=g[y];if(E&&E.pop){v(E[0],-h,-1,y);v(E[1],1,h,y);re=E[0];le=E[1]}else{v(E,-h,h,y);if(E){re=-(le=E<0?-E:E)}else{throw Error(o+y+" cannot be zero: "+E)}}}if(g.hasOwnProperty(y="CRYPTO")){E=g[y];if(E===!!E){if(E){if(typeof crypto!="undefined"&&crypto&&(crypto.getRandomValues||crypto.randomBytes)){Se=E}else{Se=!E;throw Error(o+"crypto unavailable")}}else{Se=E}}else{throw Error(o+y+" not true or false: "+E)}}if(g.hasOwnProperty(y="MODULO_MODE")){E=g[y];v(E,0,9,y);Ie=E}if(g.hasOwnProperty(y="POW_PRECISION")){E=g[y];v(E,0,h,y);ce=E}if(g.hasOwnProperty(y="FORMAT")){E=g[y];if(typeof E=="object")At=E;else throw Error(o+y+" not an object: "+E)}if(g.hasOwnProperty(y="ALPHABET")){E=g[y];if(typeof E=="string"&&!/^.?$|[+\-.\s]|(.).*\1/.test(E)){Er=E.slice(0,10)=="0123456789";Ct=E}else{throw Error(o+y+" invalid: "+E)}}}else{throw Error(o+"Object expected: "+g)}}return{DECIMAL_PLACES:Y,ROUNDING_MODE:Q,EXPONENTIAL_AT:[oe,ee],RANGE:[re,le],CRYPTO:Se,MODULO_MODE:Ie,POW_PRECISION:ce,FORMAT:At,ALPHABET:Ct}};b.isBigNumber=function(g){if(!g||g._isBigNumber!==true)return false;if(!b.DEBUG)return true;var y,E,N=g.c,S=g.e,w=g.s;e:if({}.toString.call(N)=="[object Array]"){if((w===1||w===-1)&&S>=-h&&S<=h&&S===r(S)){if(N[0]===0){if(S===0&&N.length===1)return true;break e}y=(S+1)%c;if(y<1)y+=c;if(String(N[0]).length==y){for(y=0;y<N.length;y++){E=N[y];if(E<0||E>=u||E!==r(E))break e}if(E!==0)return true}}}else if(N===null&&S===null&&(w===null||w===1||w===-1)){return true}throw Error(o+"Invalid BigNumber: "+g)};b.maximum=b.max=function(){return Ba(arguments,-1)};b.minimum=b.min=function(){return Ba(arguments,1)};b.random=(function(){var g=9007199254740992;var y=Math.random()*g&2097151?function(){return r(Math.random()*g)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(E){var N,S,w,x,C,I=0,M=[],P=new b($);if(E==null)E=Y;else v(E,0,h);x=i(E/c);if(Se){if(crypto.getRandomValues){N=crypto.getRandomValues(new Uint32Array(x*=2));for(;I<x;){C=N[I]*131072+(N[I+1]>>>11);if(C>=9e15){S=crypto.getRandomValues(new Uint32Array(2));N[I]=S[0];N[I+1]=S[1]}else{M.push(C%1e14);I+=2}}I=x/2}else if(crypto.randomBytes){N=crypto.randomBytes(x*=7);for(;I<x;){C=(N[I]&31)*281474976710656+N[I+1]*1099511627776+N[I+2]*4294967296+N[I+3]*16777216+(N[I+4]<<16)+(N[I+5]<<8)+N[I+6];if(C>=9e15){crypto.randomBytes(7).copy(N,I)}else{M.push(C%1e14);I+=7}}I=x/7}else{Se=false;throw Error(o+"crypto unavailable")}}if(!Se){for(;I<x;){C=y();if(C<9e15)M[I++]=C%1e14}}x=M[--I];E%=c;if(x&&E){C=f[c-E];M[I]=r(x/C)*C}for(;M[I]===0;M.pop(),I--);if(I<0){M=[w=0]}else{for(w=-1;M[0]===0;M.splice(0,1),w-=c);for(I=1,C=M[0];C>=10;C/=10,I++);if(I<c)w-=c-I}P.e=w;P.c=M;return P}})();b.sum=function(){var g=1,y=arguments,E=new b(y[0]);for(;g<y.length;)E=E.plus(y[g++]);return E};q=(function(){var g="0123456789";function y(E,N,S,w){var x,C=[0],I,M=0,P=E.length;for(;M<P;){for(I=C.length;I--;C[I]*=N);C[0]+=w.indexOf(E.charAt(M++));for(x=0;x<C.length;x++){if(C[x]>S-1){if(C[x+1]==null)C[x+1]=0;C[x+1]+=C[x]/S|0;C[x]%=S}}}return C.reverse()}return function(E,N,S,w,x){var C,I,M,P,U,J,K,te,se=E.indexOf("."),pe=Y,Z=Q;if(se>=0){P=ce;ce=0;E=E.replace(".","");te=new b(N);J=te.pow(E.length-se);ce=P;te.c=y(O(A(J.c),J.e,"0"),10,S,g);te.e=te.c.length}K=y(E,N,S,x?(C=Ct,g):(C=g,Ct));M=P=K.length;for(;K[--P]==0;K.pop());if(!K[0])return C.charAt(0);if(se<0){--M}else{J.c=K;J.e=M;J.s=w;J=R(J,te,pe,Z,S);K=J.c;U=J.r;M=J.e}I=M+pe+1;se=K[I];P=S/2;U=U||I<0||K[I+1]!=null;U=Z<4?(se!=null||U)&&(Z==0||Z==(J.s<0?3:2)):se>P||se==P&&(Z==4||U||Z==6&&K[I-1]&1||Z==(J.s<0?8:7));if(I<1||!K[0]){E=U?O(C.charAt(1),-pe,C.charAt(0)):C.charAt(0)}else{K.length=I;if(U){for(--S;++K[--I]>S;){K[I]=0;if(!I){++M;K=[1].concat(K)}}}for(P=K.length;!K[--P];);for(se=0,E="";se<=P;E+=C.charAt(K[se++]));E=O(E,M,C.charAt(0))}return E}})();R=(function(){function g(N,S,w){var x,C,I,M,P=0,U=N.length,J=S%p,K=S/p|0;for(N=N.slice();U--;){I=N[U]%p;M=N[U]/p|0;x=K*I+M*J;C=J*I+x%p*p+P;P=(C/w|0)+(x/p|0)+K*M;N[U]=C%w}if(P)N=[P].concat(N);return N}function y(N,S,w,x){var C,I;if(w!=x){I=w>x?1:-1}else{for(C=I=0;C<w;C++){if(N[C]!=S[C]){I=N[C]>S[C]?1:-1;break}}}return I}function E(N,S,w,x){var C=0;for(;w--;){N[w]-=C;C=N[w]<S[w]?1:0;N[w]=C*x+N[w]-S[w]}for(;!N[0]&&N.length>1;N.splice(0,1));}return function(N,S,w,x,C){var I,M,P,U,J,K,te,se,pe,Z,ne,me,Mn,Ar,Cr,ze,sn,ke=N.s==S.s?1:-1,Ee=N.c,ae=S.c;if(!Ee||!Ee[0]||!ae||!ae[0]){return new b(!N.s||!S.s||(Ee?ae&&Ee[0]==ae[0]:!ae)?NaN:Ee&&Ee[0]==0||!ae?ke*0:ke/0)}se=new b(ke);pe=se.c=[];M=N.e-S.e;ke=w+M+1;if(!C){C=u;M=_(N.e/c)-_(S.e/c);ke=ke/c|0}for(P=0;ae[P]==(Ee[P]||0);P++);if(ae[P]>(Ee[P]||0))M--;if(ke<0){pe.push(1);U=true}else{Ar=Ee.length;ze=ae.length;P=0;ke+=2;J=r(C/(ae[0]+1));if(J>1){ae=g(ae,J,C);Ee=g(Ee,J,C);ze=ae.length;Ar=Ee.length}Mn=ze;Z=Ee.slice(0,ze);ne=Z.length;for(;ne<ze;Z[ne++]=0);sn=ae.slice();sn=[0].concat(sn);Cr=ae[0];if(ae[1]>=C/2)Cr++;do{J=0;I=y(ae,Z,ze,ne);if(I<0){me=Z[0];if(ze!=ne)me=me*C+(Z[1]||0);J=r(me/Cr);if(J>1){if(J>=C)J=C-1;K=g(ae,J,C);te=K.length;ne=Z.length;while(y(K,Z,te,ne)==1){J--;E(K,ze<te?sn:ae,te,C);te=K.length;I=1}}else{if(J==0){I=J=1}K=ae.slice();te=K.length}if(te<ne)K=[0].concat(K);E(Z,K,ne,C);ne=Z.length;if(I==-1){while(y(ae,Z,ze,ne)<1){J++;E(Z,ze<ne?sn:ae,ne,C);ne=Z.length}}}else if(I===0){J++;Z=[0]}pe[P++]=J;if(Z[0]){Z[ne++]=Ee[Mn]||0}else{Z=[Ee[Mn]];ne=1}}while((Mn++<Ar||Z[0]!=null)&&ke--);U=Z[0]!=null;if(!pe[0])pe.splice(0,1)}if(C==u){for(P=1,ke=pe[0];ke>=10;ke/=10,P++);Me(se,w+(se.e=P+M*c-1)+1,x,U)}else{se.e=M;se.r=+U}return se}})();function _r(g,y,E,N){var S,w,x,C,I;if(E==null)E=Q;else v(E,0,8);if(!g.c)return g.toString();S=g.c[0];x=g.e;if(y==null){I=A(g.c);I=N==1||N==2&&(x<=oe||x>=ee)?D(I,x):O(I,x,"0")}else{g=Me(new b(g),y,E);w=g.e;I=A(g.c);C=I.length;if(N==1||N==2&&(y<=w||w<=oe)){for(;C<y;I+="0",C++);I=D(I,w)}else{y-=x+(N===2&&w>x);I=O(I,w,"0");if(w+1>C){if(--y>0)for(I+=".";y--;I+="0");}else{y+=w-C;if(y>0){if(w+1==C)I+=".";for(;y--;I+="0");}}}}return g.s<0&&S?"-"+I:I}function Ba(g,y){var E,N,S=1,w=new b(g[0]);for(;S<g.length;S++){N=new b(g[S]);if(!N.s||(E=T(w,N))===y||E===0&&w.s===y){w=N}}return w}function Tr(g,y,E){var N=1,S=y.length;for(;!y[--S];y.pop());for(S=y[0];S>=10;S/=10,N++);if((E=N+E*c-1)>le){g.c=g.e=null}else if(E<re){g.c=[g.e=0]}else{g.e=E;g.c=y}return g}V=(function(){var g=/^(-?)0([xbo])(?=\w[\w.]*$)/i,y=/^([^.]+)\.$/,E=/^\.([^.]+)$/,N=/^-?(Infinity|NaN)$/,S=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(w,x,C,I){var M,P=C?x:x.replace(S,"");if(N.test(P)){w.s=isNaN(P)?null:P<0?-1:1}else{if(!C){P=P.replace(g,function(U,J,K){M=(K=K.toLowerCase())=="x"?16:K=="b"?2:8;return!I||I==M?J:U});if(I){M=I;P=P.replace(y,"$1").replace(E,"0.$1")}if(x!=P)return new b(P,M)}if(b.DEBUG){throw Error(o+"Not a"+(I?" base "+I:"")+" number: "+x)}w.s=null}w.c=w.e=null}})();function Me(g,y,E,N){var S,w,x,C,I,M,P,U=g.c,J=f;if(U){e:{for(S=1,C=U[0];C>=10;C/=10,S++);w=y-S;if(w<0){w+=c;x=y;I=U[M=0];P=r(I/J[S-x-1]%10)}else{M=i((w+1)/c);if(M>=U.length){if(N){for(;U.length<=M;U.push(0));I=P=0;S=1;w%=c;x=w-c+1}else{break e}}else{I=C=U[M];for(S=1;C>=10;C/=10,S++);w%=c;x=w-c+S;P=x<0?0:r(I/J[S-x-1]%10)}}N=N||y<0||U[M+1]!=null||(x<0?I:I%J[S-x-1]);N=E<4?(P||N)&&(E==0||E==(g.s<0?3:2)):P>5||P==5&&(E==4||N||E==6&&(w>0?x>0?I/J[S-x]:0:U[M-1])%10&1||E==(g.s<0?8:7));if(y<1||!U[0]){U.length=0;if(N){y-=g.e+1;U[0]=J[(c-y%c)%c];g.e=-y||0}else{U[0]=g.e=0}return g}if(w==0){U.length=M;C=1;M--}else{U.length=M+1;C=J[c-w];U[M]=x>0?r(I/J[S-x]%J[x])*C:0}if(N){for(;;){if(M==0){for(w=1,x=U[0];x>=10;x/=10,w++);x=U[0]+=C;for(C=1;x>=10;x/=10,C++);if(w!=C){g.e++;if(U[0]==u)U[0]=1}break}else{U[M]+=C;if(U[M]!=u)break;U[M--]=0;C=1}}}for(w=U.length;U[--w]===0;U.pop());}if(g.e>le){g.c=g.e=null}else if(g.e<re){g.c=[g.e=0]}}return g}function nt(g){var y,E=g.e;if(E===null)return g.toString();y=A(g.c);y=E<=oe||E>=ee?D(y,E):O(y,E,"0");return g.s<0?"-"+y:y}k.absoluteValue=k.abs=function(){var g=new b(this);if(g.s<0)g.s=1;return g};k.comparedTo=function(g,y){return T(this,new b(g,y))};k.decimalPlaces=k.dp=function(g,y){var E,N,S,w=this;if(g!=null){v(g,0,h);if(y==null)y=Q;else v(y,0,8);return Me(new b(w),g+w.e+1,y)}if(!(E=w.c))return null;N=((S=E.length-1)-_(this.e/c))*c;if(S=E[S])for(;S%10==0;S/=10,N--);if(N<0)N=0;return N};k.dividedBy=k.div=function(g,y){return R(this,new b(g,y),Y,Q)};k.dividedToIntegerBy=k.idiv=function(g,y){return R(this,new b(g,y),0,1)};k.exponentiatedBy=k.pow=function(g,y){var E,N,S,w,x,C,I,M,P,U=this;g=new b(g);if(g.c&&!g.isInteger()){throw Error(o+"Exponent not an integer: "+nt(g))}if(y!=null)y=new b(y);C=g.e>14;if(!U.c||!U.c[0]||U.c[0]==1&&!U.e&&U.c.length==1||!g.c||!g.c[0]){P=new b(Math.pow(+nt(U),C?g.s*(2-G(g)):+nt(g)));return y?P.mod(y):P}I=g.s<0;if(y){if(y.c?!y.c[0]:!y.s)return new b(NaN);N=!I&&U.isInteger()&&y.isInteger();if(N)U=U.mod(y)}else if(g.e>9&&(U.e>0||U.e<-1||(U.e==0?U.c[0]>1||C&&U.c[1]>=24e7:U.c[0]<8e13||C&&U.c[0]<=9999975e7))){w=U.s<0&&G(g)?-0:0;if(U.e>-1)w=1/w;return new b(I?1/w:w)}else if(ce){w=i(ce/c+2)}if(C){E=new b(.5);if(I)g.s=1;M=G(g)}else{S=Math.abs(+nt(g));M=S%2}P=new b($);for(;;){if(M){P=P.times(U);if(!P.c)break;if(w){if(P.c.length>w)P.c.length=w}else if(N){P=P.mod(y)}}if(S){S=r(S/2);if(S===0)break;M=S%2}else{g=g.times(E);Me(g,g.e+1,1);if(g.e>14){M=G(g)}else{S=+nt(g);if(S===0)break;M=S%2}}U=U.times(U);if(w){if(U.c&&U.c.length>w)U.c.length=w}else if(N){U=U.mod(y)}}if(N)return P;if(I)P=$.div(P);return y?P.mod(y):w?Me(P,ce,Q,x):P};k.integerValue=function(g){var y=new b(this);if(g==null)g=Q;else v(g,0,8);return Me(y,y.e+1,g)};k.isEqualTo=k.eq=function(g,y){return T(this,new b(g,y))===0};k.isFinite=function(){return!!this.c};k.isGreaterThan=k.gt=function(g,y){return T(this,new b(g,y))>0};k.isGreaterThanOrEqualTo=k.gte=function(g,y){return(y=T(this,new b(g,y)))===1||y===0};k.isInteger=function(){return!!this.c&&_(this.e/c)>this.c.length-2};k.isLessThan=k.lt=function(g,y){return T(this,new b(g,y))<0};k.isLessThanOrEqualTo=k.lte=function(g,y){return(y=T(this,new b(g,y)))===-1||y===0};k.isNaN=function(){return!this.s};k.isNegative=function(){return this.s<0};k.isPositive=function(){return this.s>0};k.isZero=function(){return!!this.c&&this.c[0]==0};k.minus=function(g,y){var E,N,S,w,x=this,C=x.s;g=new b(g,y);y=g.s;if(!C||!y)return new b(NaN);if(C!=y){g.s=-y;return x.plus(g)}var I=x.e/c,M=g.e/c,P=x.c,U=g.c;if(!I||!M){if(!P||!U)return P?(g.s=-y,g):new b(U?x:NaN);if(!P[0]||!U[0]){return U[0]?(g.s=-y,g):new b(P[0]?x:Q==3?-0:0)}}I=_(I);M=_(M);P=P.slice();if(C=I-M){if(w=C<0){C=-C;S=P}else{M=I;S=U}S.reverse();for(y=C;y--;S.push(0));S.reverse()}else{N=(w=(C=P.length)<(y=U.length))?C:y;for(C=y=0;y<N;y++){if(P[y]!=U[y]){w=P[y]<U[y];break}}}if(w){S=P;P=U;U=S;g.s=-g.s}y=(N=U.length)-(E=P.length);if(y>0)for(;y--;P[E++]=0);y=u-1;for(;N>C;){if(P[--N]<U[N]){for(E=N;E&&!P[--E];P[E]=y);--P[E];P[N]+=u}P[N]-=U[N]}for(;P[0]==0;P.splice(0,1),--M);if(!P[0]){g.s=Q==3?-1:1;g.c=[g.e=0];return g}return Tr(g,P,M)};k.modulo=k.mod=function(g,y){var E,N,S=this;g=new b(g,y);if(!S.c||!g.s||g.c&&!g.c[0]){return new b(NaN)}else if(!g.c||S.c&&!S.c[0]){return new b(S)}if(Ie==9){N=g.s;g.s=1;E=R(S,g,0,3);g.s=N;E.s*=N}else{E=R(S,g,0,Ie)}g=S.minus(E.times(g));if(!g.c[0]&&Ie==1)g.s=S.s;return g};k.multipliedBy=k.times=function(g,y){var E,N,S,w,x,C,I,M,P,U,J,K,te,se,pe,Z=this,ne=Z.c,me=(g=new b(g,y)).c;if(!ne||!me||!ne[0]||!me[0]){if(!Z.s||!g.s||ne&&!ne[0]&&!me||me&&!me[0]&&!ne){g.c=g.e=g.s=null}else{g.s*=Z.s;if(!ne||!me){g.c=g.e=null}else{g.c=[0];g.e=0}}return g}N=_(Z.e/c)+_(g.e/c);g.s*=Z.s;I=ne.length;U=me.length;if(I<U){te=ne;ne=me;me=te;S=I;I=U;U=S}for(S=I+U,te=[];S--;te.push(0));se=u;pe=p;for(S=U;--S>=0;){E=0;J=me[S]%pe;K=me[S]/pe|0;for(x=I,w=S+x;w>S;){M=ne[--x]%pe;P=ne[x]/pe|0;C=K*M+P*J;M=J*M+C%pe*pe+te[w]+E;E=(M/se|0)+(C/pe|0)+K*P;te[w--]=M%se}te[w]=E}if(E){++N}else{te.splice(0,1)}return Tr(g,te,N)};k.negated=function(){var g=new b(this);g.s=-g.s||null;return g};k.plus=function(g,y){var E,N=this,S=N.s;g=new b(g,y);y=g.s;if(!S||!y)return new b(NaN);if(S!=y){g.s=-y;return N.minus(g)}var w=N.e/c,x=g.e/c,C=N.c,I=g.c;if(!w||!x){if(!C||!I)return new b(S/0);if(!C[0]||!I[0])return I[0]?g:new b(C[0]?N:S*0)}w=_(w);x=_(x);C=C.slice();if(S=w-x){if(S>0){x=w;E=I}else{S=-S;E=C}E.reverse();for(;S--;E.push(0));E.reverse()}S=C.length;y=I.length;if(S-y<0){E=I;I=C;C=E;y=S}for(S=0;y;){S=(C[--y]=C[y]+I[y]+S)/u|0;C[y]=u===C[y]?0:C[y]%u}if(S){C=[S].concat(C);++x}return Tr(g,C,x)};k.precision=k.sd=function(g,y){var E,N,S,w=this;if(g!=null&&g!==!!g){v(g,1,h);if(y==null)y=Q;else v(y,0,8);return Me(new b(w),g,y)}if(!(E=w.c))return null;S=E.length-1;N=S*c+1;if(S=E[S]){for(;S%10==0;S/=10,N--);for(S=E[0];S>=10;S/=10,N++);}if(g&&w.e+1>N)N=w.e+1;return N};k.shiftedBy=function(g){v(g,-d,d);return this.times("1e"+g)};k.squareRoot=k.sqrt=function(){var g,y,E,N,S,w=this,x=w.c,C=w.s,I=w.e,M=Y+4,P=new b("0.5");if(C!==1||!x||!x[0]){return new b(!C||C<0&&(!x||x[0])?NaN:x?w:1/0)}C=Math.sqrt(+nt(w));if(C==0||C==1/0){y=A(x);if((y.length+I)%2==0)y+="0";C=Math.sqrt(+y);I=_((I+1)/2)-(I<0||I%2);if(C==1/0){y="5e"+I}else{y=C.toExponential();y=y.slice(0,y.indexOf("e")+1)+I}E=new b(y)}else{E=new b(C+"")}if(E.c[0]){I=E.e;C=I+M;if(C<3)C=0;for(;;){S=E;E=P.times(S.plus(R(w,S,M,1)));if(A(S.c).slice(0,C)===(y=A(E.c)).slice(0,C)){if(E.e<I)--C;y=y.slice(C-3,C+1);if(y=="9999"||!N&&y=="4999"){if(!N){Me(S,S.e+Y+2,0);if(S.times(S).eq(w)){E=S;break}}M+=4;C+=4;N=1}else{if(!+y||!+y.slice(1)&&y.charAt(0)=="5"){Me(E,E.e+Y+2,1);g=!E.times(E).eq(w)}break}}}}return Me(E,E.e+Y+1,Q,g)};k.toExponential=function(g,y){if(g!=null){v(g,0,h);g++}return _r(this,g,y,1)};k.toFixed=function(g,y){if(g!=null){v(g,0,h);g=g+this.e+1}return _r(this,g,y)};k.toFormat=function(g,y,E){var N,S=this;if(E==null){if(g!=null&&y&&typeof y=="object"){E=y;y=null}else if(g&&typeof g=="object"){E=g;g=y=null}else{E=At}}else if(typeof E!="object"){throw Error(o+"Argument not an object: "+E)}N=S.toFixed(g,y);if(S.c){var w,x=N.split("."),C=+E.groupSize,I=+E.secondaryGroupSize,M=E.groupSeparator||"",P=x[0],U=x[1],J=S.s<0,K=J?P.slice(1):P,te=K.length;if(I){w=C;C=I;I=w;te-=w}if(C>0&&te>0){w=te%C||C;P=K.substr(0,w);for(;w<te;w+=C)P+=M+K.substr(w,C);if(I>0)P+=M+K.slice(w);if(J)P="-"+P}N=U?P+(E.decimalSeparator||"")+((I=+E.fractionGroupSize)?U.replace(new RegExp("\\d{"+I+"}\\B","g"),"$&"+(E.fractionGroupSeparator||"")):U):P}return(E.prefix||"")+N+(E.suffix||"")};k.toFraction=function(g){var y,E,N,S,w,x,C,I,M,P,U,J,K=this,te=K.c;if(g!=null){C=new b(g);if(!C.isInteger()&&(C.c||C.s!==1)||C.lt($)){throw Error(o+"Argument "+(C.isInteger()?"out of range: ":"not an integer: ")+nt(C))}}if(!te)return new b(K);y=new b($);M=E=new b($);N=I=new b($);J=A(te);w=y.e=J.length-K.e-1;y.c[0]=f[(x=w%c)<0?c+x:x];g=!g||C.comparedTo(y)>0?w>0?y:M:C;x=le;le=1/0;C=new b(J);I.c[0]=0;for(;;){P=R(C,y,0,1);S=E.plus(P.times(N));if(S.comparedTo(g)==1)break;E=N;N=S;M=I.plus(P.times(S=M));I=S;y=C.minus(P.times(S=y));C=S}S=R(g.minus(E),N,0,1);I=I.plus(S.times(M));E=E.plus(S.times(N));I.s=M.s=K.s;w=w*2;U=R(M,N,w,Q).minus(K).abs().comparedTo(R(I,E,w,Q).minus(K).abs())<1?[M,N]:[I,E];le=x;return U};k.toNumber=function(){return+nt(this)};k.toPrecision=function(g,y){if(g!=null)v(g,1,h);return _r(this,g,y,2)};k.toString=function(g){var y,E=this,N=E.s,S=E.e;if(S===null){if(N){y="Infinity";if(N<0)y="-"+y}else{y="NaN"}}else{if(g==null){y=S<=oe||S>=ee?D(A(E.c),S):O(A(E.c),S,"0")}else if(g===10&&Er){E=Me(new b(E),Y+S+1,Q);y=O(A(E.c),E.e,"0")}else{v(g,2,Ct.length,"Base");y=q(O(A(E.c),S,"0"),10,g,N,true)}if(N<0&&E.c[0])y="-"+y}return y};k.valueOf=k.toJSON=function(){return nt(this)};k._isBigNumber=true;if(L!=null)b.set(L);return b}function _(L){var R=L|0;return L>0||L===R?R:R-1}function A(L){var R,q,V=1,k=L.length,$=L[0]+"";for(;V<k;){R=L[V++]+"";q=c-R.length;for(;q--;R="0"+R);$+=R}for(k=$.length;$.charCodeAt(--k)===48;);return $.slice(0,k+1||1)}function T(L,R){var q,V,k=L.c,$=R.c,Y=L.s,Q=R.s,oe=L.e,ee=R.e;if(!Y||!Q)return null;q=k&&!k[0];V=$&&!$[0];if(q||V)return q?V?0:-Q:Y;if(Y!=Q)return Y;q=Y<0;V=oe==ee;if(!k||!$)return V?0:!k^q?1:-1;if(!V)return oe>ee^q?1:-1;Q=(oe=k.length)<(ee=$.length)?oe:ee;for(Y=0;Y<Q;Y++)if(k[Y]!=$[Y])return k[Y]>$[Y]^q?1:-1;return oe==ee?0:oe>ee^q?1:-1}function v(L,R,q,V){if(L<R||L>q||L!==r(L)){throw Error(o+(V||"Argument")+(typeof L=="number"?L<R||L>q?" out of range: ":" not an integer: ":" not a primitive number: ")+String(L))}}function G(L){var R=L.c.length-1;return _(L.e/c)==R&&L.c[R]%2!=0}function D(L,R){return(L.length>1?L.charAt(0)+"."+L.slice(1):L)+(R<0?"e":"e+")+R}function O(L,R,q){var V,k;if(R<0){for(k=q+".";++R;k+=q);L=k+L}else{V=L.length;if(++R>V){for(k=q,R-=V;--R;k+=q);L+=k}else if(R<V){L=L.slice(0,R)+"."+L.slice(R)}}return L}e=m();e["default"]=e.BigNumber=e;if(typeof define=="function"&&define.amd){define(function(){return e})}else if(typeof Gn!="undefined"&&Gn.exports){Gn.exports=e}else{if(!t){t=typeof self!="undefined"&&self?self:window}t.BigNumber=e}})(Tl)});var Sl=F((GS,vl)=>{var Al=Mr();var Cl=vl.exports;(function(){"use strict";function t(d){return d<10?"0"+d:d}var e=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,n=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,i,r,o={"\b":"\\b"," ":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},l;function u(d){n.lastIndex=0;return n.test(d)?'"'+d.replace(n,function(f){var p=o[f];return typeof p==="string"?p:"\\u"+("0000"+f.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+d+'"'}function c(d,f){var p,h,m,_,A=i,T,v=f[d],G=v!=null&&(v instanceof Al||Al.isBigNumber(v));if(v&&typeof v==="object"&&typeof v.toJSON==="function"){v=v.toJSON(d)}if(typeof l==="function"){v=l.call(f,d,v)}switch(typeof v){case"string":if(G){return v}else{return u(v)}case"number":return isFinite(v)?String(v):"null";case"boolean":case"null":case"bigint":return String(v);case"object":if(!v){return"null"}i+=r;T=[];if(Object.prototype.toString.apply(v)==="[object Array]"){_=v.length;for(p=0;p<_;p+=1){T[p]=c(p,v)||"null"}m=T.length===0?"[]":i?"[\n"+i+T.join(",\n"+i)+"\n"+A+"]":"["+T.join(",")+"]";i=A;return m}if(l&&typeof l==="object"){_=l.length;for(p=0;p<_;p+=1){if(typeof l[p]==="string"){h=l[p];m=c(h,v);if(m){T.push(u(h)+(i?": ":":")+m)}}}}else{Object.keys(v).forEach(function(D){var O=c(D,v);if(O){T.push(u(D)+(i?": ":":")+O)}})}m=T.length===0?"{}":i?"{\n"+i+T.join(",\n"+i)+"\n"+A+"}":"{"+T.join(",")+"}";i=A;return m}}if(typeof Cl.stringify!=="function"){Cl.stringify=function(d,f,p){var h;i="";r="";if(typeof p==="number"){for(h=0;h<p;h+=1){r+=" "}}else if(typeof p==="string"){r=p}l=f;if(f&&typeof f!=="function"&&(typeof f!=="object"||typeof f.length!=="number")){throw new Error("JSON.stringify")}return c("",{"":d})}}})()});var wl=F((OS,Il)=>{var On=null;var Cp=/(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])/;var vp=/(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)/;var Sp=function(t){"use strict";var e={strict:false,storeAsString:false,alwaysParseAsBig:false,useNativeBigInt:false,protoAction:"error",constructorAction:"error"};if(t!==void 0&&t!==null){if(t.strict===true){e.strict=true}if(t.storeAsString===true){e.storeAsString=true}e.alwaysParseAsBig=t.alwaysParseAsBig===true?t.alwaysParseAsBig:false;e.useNativeBigInt=t.useNativeBigInt===true?t.useNativeBigInt:false;if(typeof t.constructorAction!=="undefined"){if(t.constructorAction==="error"||t.constructorAction==="ignore"||t.constructorAction==="preserve"){e.constructorAction=t.constructorAction}else{throw new Error(`Incorrect value for constructorAction option, must be "error", "ignore" or undefined but passed ${t.constructorAction}`)}}if(typeof t.protoAction!=="undefined"){if(t.protoAction==="error"||t.protoAction==="ignore"||t.protoAction==="preserve"){e.protoAction=t.protoAction}else{throw new Error(`Incorrect value for protoAction option, must be "error", "ignore" or undefined but passed ${t.protoAction}`)}}}var n,i,r={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:"\n",r:"\r",t:" "},o,l=function(A){throw{name:"SyntaxError",message:A,at:n,text:o}},u=function(A){if(A&&A!==i){l("Expected '"+A+"' instead of '"+i+"'")}i=o.charAt(n);n+=1;return i},c=function(){var A,T="";if(i==="-"){T="-";u("-")}while(i>="0"&&i<="9"){T+=i;u()}if(i==="."){T+=".";while(u()&&i>="0"&&i<="9"){T+=i}}if(i==="e"||i==="E"){T+=i;u();if(i==="-"||i==="+"){T+=i;u()}while(i>="0"&&i<="9"){T+=i;u()}}A=+T;if(!isFinite(A)){l("Bad number")}else{if(On==null)On=Mr();if(T.length>15)return e.storeAsString?T:e.useNativeBigInt?BigInt(T):new On(T);else return!e.alwaysParseAsBig?A:e.useNativeBigInt?BigInt(A):new On(A)}},d=function(){var A,T,v="",G;if(i==='"'){var D=n;while(u()){if(i==='"'){if(n-1>D)v+=o.substring(D,n-1);u();return v}if(i==="\\"){if(n-1>D)v+=o.substring(D,n-1);u();if(i==="u"){G=0;for(T=0;T<4;T+=1){A=parseInt(u(),16);if(!isFinite(A)){break}G=G*16+A}v+=String.fromCharCode(G)}else if(typeof r[i]==="string"){v+=r[i]}else{break}D=n}}}l("Bad string")},f=function(){while(i&&i<=" "){u()}},p=function(){switch(i){case"t":u("t");u("r");u("u");u("e");return true;case"f":u("f");u("a");u("l");u("s");u("e");return false;case"n":u("n");u("u");u("l");u("l");return null}l("Unexpected '"+i+"'")},h,m=function(){var A=[];if(i==="["){u("[");f();if(i==="]"){u("]");return A}while(i){A.push(h());f();if(i==="]"){u("]");return A}u(",");f()}}l("Bad array")},_=function(){var A,T=Object.create(null);if(i==="{"){u("{");f();if(i==="}"){u("}");return T}while(i){A=d();f();u(":");if(e.strict===true&&Object.hasOwnProperty.call(T,A)){l('Duplicate key "'+A+'"')}if(Cp.test(A)===true){if(e.protoAction==="error"){l("Object contains forbidden prototype property")}else if(e.protoAction==="ignore"){h()}else{T[A]=h()}}else if(vp.test(A)===true){if(e.constructorAction==="error"){l("Object contains forbidden constructor property")}else if(e.constructorAction==="ignore"){h()}else{T[A]=h()}}else{T[A]=h()}f();if(i==="}"){u("}");return T}u(",");f()}}l("Bad object")};h=function(){f();switch(i){case"{":return _();case"[":return m();case'"':return d();case"-":return c();default:return i>="0"&&i<="9"?c():p()}};return function(A,T){var v;o=A+"";n=0;i=" ";v=h();f();if(i){l("Syntax error")}return typeof T==="function"?(function G(D,O){var L,R,q=D[O];if(q&&typeof q==="object"){Object.keys(q).forEach(function(V){R=G(q,V);if(R!==void 0){q[V]=R}else{delete q[V]}})}return T.call(D,O,q)})({"":v},""):v}};Il.exports=Sp});var Nl=F((bS,bn)=>{var Rl=Sl().stringify;var Pl=wl();bn.exports=function(t){return{parse:Pl(t),stringify:Rl}};bn.exports.parse=Pl();bn.exports.stringify=Rl});var kr=F(be=>{"use strict";Object.defineProperty(be,"__esModule",{value:true});be.GCE_LINUX_BIOS_PATHS=void 0;be.isGoogleCloudServerless=xl;be.isGoogleComputeEngineLinux=Dl;be.isGoogleComputeEngineMACAddress=Ul;be.isGoogleComputeEngine=Ll;be.detectGCPResidency=wp;var Ml=z("fs");var kl=z("os");be.GCE_LINUX_BIOS_PATHS={BIOS_DATE:"/sys/class/dmi/id/bios_date",BIOS_VENDOR:"/sys/class/dmi/id/bios_vendor"};var Ip=/^42:01/;function xl(){const t=process.env.CLOUD_RUN_JOB||process.env.FUNCTION_NAME||process.env.K_SERVICE;return!!t}function Dl(){if((0,kl.platform)()!=="linux")return false;try{(0,Ml.statSync)(be.GCE_LINUX_BIOS_PATHS.BIOS_DATE);const t=(0,Ml.readFileSync)(be.GCE_LINUX_BIOS_PATHS.BIOS_VENDOR,"utf8");return/Google/.test(t)}catch{return false}}function Ul(){const t=(0,kl.networkInterfaces)();for(const e of Object.values(t)){if(!e)continue;for(const{mac:n}of e){if(Ip.test(n)){return true}}}return false}function Ll(){return Dl()||Ul()}function wp(){return xl()||Ll()}});var Gl=F(Fn=>{"use strict";Object.defineProperty(Fn,"__esModule",{value:true});Fn.Colours=void 0;var ye=class t{static isEnabled(e){return e&&e.isTTY&&(typeof e.getColorDepth==="function"?e.getColorDepth()>2:true)}static refresh(){t.enabled=t.isEnabled(process===null||process===void 0?void 0:process.stderr);if(!this.enabled){t.reset="";t.bright="";t.dim="";t.red="";t.green="";t.yellow="";t.blue="";t.magenta="";t.cyan="";t.white="";t.grey=""}else{t.reset="\x1B[0m";t.bright="\x1B[1m";t.dim="\x1B[2m";t.red="\x1B[31m";t.green="\x1B[32m";t.yellow="\x1B[33m";t.blue="\x1B[34m";t.magenta="\x1B[35m";t.cyan="\x1B[36m";t.white="\x1B[37m";t.grey="\x1B[90m"}}};Fn.Colours=ye;ye.enabled=false;ye.reset="";ye.bright="";ye.dim="";ye.red="";ye.green="";ye.yellow="";ye.blue="";ye.magenta="";ye.cyan="";ye.white="";ye.grey="";ye.refresh()});var ql=F(ie=>{"use strict";var Rp=ie&&ie.__createBinding||(Object.create?(function(t,e,n,i){if(i===void 0)i=n;var r=Object.getOwnPropertyDescriptor(e,n);if(!r||("get"in r?!e.__esModule:r.writable||r.configurable)){r={enumerable:true,get:function(){return e[n]}}}Object.defineProperty(t,i,r)}):(function(t,e,n,i){if(i===void 0)i=n;t[i]=e[n]}));var Pp=ie&&ie.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:true,value:e})}):function(t,e){t["default"]=e});var Ol=ie&&ie.__importStar||(function(){var t=function(e){t=Object.getOwnPropertyNames||function(n){var i=[];for(var r in n)if(Object.prototype.hasOwnProperty.call(n,r))i[i.length]=r;return i};return t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null){for(var i=t(e),r=0;r<i.length;r++)if(i[r]!=="default")Rp(n,e,i[r])}Pp(n,e);return n}})();Object.defineProperty(ie,"__esModule",{value:true});ie.env=ie.DebugLogBackendBase=ie.placeholder=ie.AdhocDebugLogger=ie.LogSeverity=void 0;ie.getNodeBackend=Dr;ie.getDebugBackend=Mp;ie.getStructuredBackend=kp;ie.setBackend=xp;ie.log=Fl;var Np=z("events");var ln=Ol(z("process"));var bl=Ol(z("util"));var we=Gl();var Fe;(function(t){t["DEFAULT"]="DEFAULT";t["DEBUG"]="DEBUG";t["INFO"]="INFO";t["WARNING"]="WARNING";t["ERROR"]="ERROR"})(Fe||(ie.LogSeverity=Fe={}));var un=class extends Np.EventEmitter{constructor(e,n){super();this.namespace=e;this.upstream=n;this.func=Object.assign(this.invoke.bind(this),{instance:this,on:(i,r)=>this.on(i,r)});this.func.debug=(...i)=>this.invokeSeverity(Fe.DEBUG,...i);this.func.info=(...i)=>this.invokeSeverity(Fe.INFO,...i);this.func.warn=(...i)=>this.invokeSeverity(Fe.WARNING,...i);this.func.error=(...i)=>this.invokeSeverity(Fe.ERROR,...i);this.func.sublog=i=>Fl(i,this.func)}invoke(e,...n){if(this.upstream){try{this.upstream(e,...n)}catch(i){}}try{this.emit("log",e,n)}catch(i){}}invokeSeverity(e,...n){this.invoke({severity:e},...n)}};ie.AdhocDebugLogger=un;ie.placeholder=new un("",()=>{}).func;var Ut=class{constructor(){var e;this.cached=new Map;this.filters=[];this.filtersSet=false;let n=(e=ln.env[ie.env.nodeEnables])!==null&&e!==void 0?e:"*";if(n==="all"){n="*"}this.filters=n.split(",")}log(e,n,...i){try{if(!this.filtersSet){this.setFilters();this.filtersSet=true}let r=this.cached.get(e);if(!r){r=this.makeLogger(e);this.cached.set(e,r)}r(n,...i)}catch(r){console.error(r)}}};ie.DebugLogBackendBase=Ut;var xr=class extends Ut{constructor(){super(...arguments);this.enabledRegexp=/.*/g}isEnabled(e){return this.enabledRegexp.test(e)}makeLogger(e){if(!this.enabledRegexp.test(e)){return()=>{}}return(n,...i)=>{var r;const o=`${we.Colours.green}${e}${we.Colours.reset}`;const l=`${we.Colours.yellow}${ln.pid}${we.Colours.reset}`;let u;switch(n.severity){case Fe.ERROR:u=`${we.Colours.red}${n.severity}${we.Colours.reset}`;break;case Fe.INFO:u=`${we.Colours.magenta}${n.severity}${we.Colours.reset}`;break;case Fe.WARNING:u=`${we.Colours.yellow}${n.severity}${we.Colours.reset}`;break;default:u=(r=n.severity)!==null&&r!==void 0?r:Fe.DEFAULT;break}const c=bl.formatWithOptions({colors:we.Colours.enabled},...i);const d=Object.assign({},n);delete d.severity;const f=Object.getOwnPropertyNames(d).length?JSON.stringify(d):"";const p=f?`${we.Colours.grey}${f}${we.Colours.reset}`:"";console.error("%s [%s|%s] %s%s",l,o,u,c,f?` ${p}`:"")}}setFilters(){const e=this.filters.join(",");const n=e.replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^");this.enabledRegexp=new RegExp(`^${n}$`,"i")}};function Dr(){return new xr}var Ur=class extends Ut{constructor(e){super();this.debugPkg=e}makeLogger(e){const n=this.debugPkg(e);return(i,...r)=>{n(r[0],...r.slice(1))}}setFilters(){var e;const n=(e=ln.env["NODE_DEBUG"])!==null&&e!==void 0?e:"";ln.env["NODE_DEBUG"]=`${n}${n?",":""}${this.filters.join(",")}`}};function Mp(t){return new Ur(t)}var Lr=class extends Ut{constructor(e){var n;super();this.upstream=(n=e)!==null&&n!==void 0?n:void 0}makeLogger(e){var n;const i=(n=this.upstream)===null||n===void 0?void 0:n.makeLogger(e);return(r,...o)=>{var l;const u=(l=r.severity)!==null&&l!==void 0?l:Fe.INFO;const c=Object.assign({severity:u,message:bl.format(...o)},r);const d=JSON.stringify(c);if(i){i(r,d)}else{console.log("%s",d)}}}setFilters(){var e;(e=this.upstream)===null||e===void 0?void 0:e.setFilters()}};function kp(t){return new Lr(t)}ie.env={nodeEnables:"GOOGLE_SDK_NODE_LOGGING"};var Gr=new Map;var Re=void 0;function xp(t){Re=t;Gr.clear()}function Fl(t,e){if(!Re){const r=ln.env[ie.env.nodeEnables];if(!r){return ie.placeholder}}if(!t){return ie.placeholder}if(e){t=`${e.instance.namespace}:${t}`}const n=Gr.get(t);if(n){return n.func}if(Re===null){return ie.placeholder}else if(Re===void 0){Re=Dr()}const i=(()=>{let r=void 0;const o=new un(t,(l,...u)=>{if(r!==Re){if(Re===null){return}else if(Re===void 0){Re=Dr()}r=Re}Re===null||Re===void 0?void 0:Re.log(t,l,...u)});return o})();Gr.set(t,i);return i.func}});var Or=F(wt=>{"use strict";var Dp=wt&&wt.__createBinding||(Object.create?(function(t,e,n,i){if(i===void 0)i=n;var r=Object.getOwnPropertyDescriptor(e,n);if(!r||("get"in r?!e.__esModule:r.writable||r.configurable)){r={enumerable:true,get:function(){return e[n]}}}Object.defineProperty(t,i,r)}):(function(t,e,n,i){if(i===void 0)i=n;t[i]=e[n]}));var Up=wt&&wt.__exportStar||function(t,e){for(var n in t)if(n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n))Dp(e,t,n)};Object.defineProperty(wt,"__esModule",{value:true});Up(ql(),wt)});var dn=F(W=>{"use strict";var Vl=W&&W.__createBinding||(Object.create?(function(t,e,n,i){if(i===void 0)i=n;var r=Object.getOwnPropertyDescriptor(e,n);if(!r||("get"in r?!e.__esModule:r.writable||r.configurable)){r={enumerable:true,get:function(){return e[n]}}}Object.defineProperty(t,i,r)}):(function(t,e,n,i){if(i===void 0)i=n;t[i]=e[n]}));var Lp=W&&W.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:true,value:e})}):function(t,e){t["default"]=e});var Gp=W&&W.__importStar||(function(){var t=function(e){t=Object.getOwnPropertyNames||function(n){var i=[];for(var r in n)if(Object.prototype.hasOwnProperty.call(n,r))i[i.length]=r;return i};return t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null){for(var i=t(e),r=0;r<i.length;r++)if(i[r]!=="default")Vl(n,e,i[r])}Lp(n,e);return n}})();var Op=W&&W.__exportStar||function(t,e){for(var n in t)if(n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n))Vl(e,t,n)};Object.defineProperty(W,"__esModule",{value:true});W.gcpResidencyCache=W.METADATA_SERVER_DETECTION=W.HEADERS=W.HEADER_VALUE=W.HEADER_NAME=W.SECONDARY_HOST_ADDRESS=W.HOST_ADDRESS=W.BASE_PATH=void 0;W.instance=Bp;W.project=$p;W.universe=Jp;W.bulk=Kp;W.isAvailable=Yp;W.resetIsAvailableCache=zp;W.getGCPResidency=qr;W.setGCPResidency=Bl;W.requestTimeout=$l;var br=ge();var bp=Nl();var Fp=kr();var qp=Gp(Or());W.BASE_PATH="/computeMetadata/v1";W.HOST_ADDRESS="http://169.254.169.254";W.SECONDARY_HOST_ADDRESS="http://metadata.google.internal.";W.HEADER_NAME="Metadata-Flavor";W.HEADER_VALUE="Google";W.HEADERS=Object.freeze({[W.HEADER_NAME]:W.HEADER_VALUE});var Hl=qp.log("gcp-metadata");W.METADATA_SERVER_DETECTION=Object.freeze({"assume-present":"don't try to ping the metadata server, but assume it's present",none:"don't try to ping the metadata server, but don't try to use it either","bios-only":"treat the result of a BIOS probe as canonical (don't fall back to pinging)","ping-only":"skip the BIOS probe, and go straight to pinging"});function Fr(t){if(!t){t=process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST||W.HOST_ADDRESS}if(!/^https?:\/\//.test(t)){t=`http://${t}`}return new URL(W.BASE_PATH,t).href}function Hp(t){Object.keys(t).forEach(e=>{switch(e){case"params":case"property":case"headers":break;case"qs":throw new Error("'qs' is not a valid configuration option. Please use 'params' instead.");default:throw new Error(`'${e}' is not a valid configuration option.`)}})}async function cn(t,e={},n=3,i=false){const r=new Headers(W.HEADERS);let o="";let l={};if(typeof t==="object"){const p=t;new Headers(p.headers).forEach((h,m)=>r.set(m,h));o=p.metadataKey;l=p.params||l;n=p.noResponseRetries||n;i=p.fastFail||i}else{o=t}if(typeof e==="string"){o+=`/${e}`}else{Hp(e);if(e.property){o+=`/${e.property}`}new Headers(e.headers).forEach((p,h)=>r.set(h,p));l=e.params||l}const u=i?Vp:br.request;const c={url:`${Fr()}/${o}`,headers:r,retryConfig:{noResponseRetries:n},params:l,responseType:"text",timeout:$l()};Hl.info("instance request %j",c);const d=await u(c);Hl.info("instance metadata is %s",d.data);const f=d.headers.get(W.HEADER_NAME);if(f!==W.HEADER_VALUE){throw new RangeError(`Invalid response from metadata service: incorrect ${W.HEADER_NAME} header. Expected '${W.HEADER_VALUE}', got ${f?`'${f}'`:"no header"}`)}if(typeof d.data==="string"){try{return bp.parse(d.data)}catch{}}return d.data}async function Vp(t){const e={...t,url:t.url?.toString().replace(Fr(),Fr(W.SECONDARY_HOST_ADDRESS))};const n=(0,br.request)(t);const i=(0,br.request)(e);return Promise.any([n,i])}function Bp(t){return cn("instance",t)}function $p(t){return cn("project",t)}function Jp(t){return cn("universe",t)}async function Kp(t){const e={};await Promise.all(t.map(n=>{return(async()=>{const i=await cn(n);const r=n.metadataKey;e[r]=i})()}));return e}function Wp(){return process.env.DETECT_GCP_RETRIES?Number(process.env.DETECT_GCP_RETRIES):0}var qn;async function Yp(){if(process.env.METADATA_SERVER_DETECTION){const t=process.env.METADATA_SERVER_DETECTION.trim().toLocaleLowerCase();if(!(t in W.METADATA_SERVER_DETECTION)){throw new RangeError(`Unknown \`METADATA_SERVER_DETECTION\` env variable. Got \`${t}\`, but it should be \`${Object.keys(W.METADATA_SERVER_DETECTION).join("`, `")}\`, or unset`)}switch(t){case"assume-present":return true;case"none":return false;case"bios-only":return qr();case"ping-only":}}try{if(qn===void 0){qn=cn("instance",void 0,Wp(),!(process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST))}await qn;return true}catch(t){const e=t;if(process.env.DEBUG_AUTH){console.info(e)}if(e.type==="request-timeout"){return false}if(e.response&&e.response.status===404){return false}else{if(!(e.response&&e.response.status===404)&&(!e.code||!["EHOSTDOWN","EHOSTUNREACH","ENETUNREACH","ENOENT","ENOTFOUND","ECONNREFUSED"].includes(e.code.toString()))){let n="UNKNOWN";if(e.code)n=e.code.toString();process.emitWarning(`received unexpected error = ${e.message} code = ${n}`,"MetadataLookupWarning")}return false}}}function zp(){qn=void 0}W.gcpResidencyCache=null;function qr(){if(W.gcpResidencyCache===null){Bl()}return W.gcpResidencyCache}function Bl(t=null){W.gcpResidencyCache=t!==null?t:(0,Fp.detectGCPResidency)()}function $l(){return qr()?0:3e3}Op(kr(),W)});var Wl=F(Hn=>{"use strict";Hn.byteLength=Qp;Hn.toByteArray=jp;Hn.fromByteArray=nh;var Xe=[];var Ue=[];var Xp=typeof Uint8Array!=="undefined"?Uint8Array:Array;var Hr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(Rt=0,Jl=Hr.length;Rt<Jl;++Rt){Xe[Rt]=Hr[Rt];Ue[Hr.charCodeAt(Rt)]=Rt}var Rt;var Jl;Ue["-".charCodeAt(0)]=62;Ue["_".charCodeAt(0)]=63;function Kl(t){var e=t.length;if(e%4>0){throw new Error("Invalid string. Length must be a multiple of 4")}var n=t.indexOf("=");if(n===-1)n=e;var i=n===e?0:4-n%4;return[n,i]}function Qp(t){var e=Kl(t);var n=e[0];var i=e[1];return(n+i)*3/4-i}function Zp(t,e,n){return(e+n)*3/4-n}function jp(t){var e;var n=Kl(t);var i=n[0];var r=n[1];var o=new Xp(Zp(t,i,r));var l=0;var u=r>0?i-4:i;var c;for(c=0;c<u;c+=4){e=Ue[t.charCodeAt(c)]<<18|Ue[t.charCodeAt(c+1)]<<12|Ue[t.charCodeAt(c+2)]<<6|Ue[t.charCodeAt(c+3)];o[l++]=e>>16&255;o[l++]=e>>8&255;o[l++]=e&255}if(r===2){e=Ue[t.charCodeAt(c)]<<2|Ue[t.charCodeAt(c+1)]>>4;o[l++]=e&255}if(r===1){e=Ue[t.charCodeAt(c)]<<10|Ue[t.charCodeAt(c+1)]<<4|Ue[t.charCodeAt(c+2)]>>2;o[l++]=e>>8&255;o[l++]=e&255}return o}function eh(t){return Xe[t>>18&63]+Xe[t>>12&63]+Xe[t>>6&63]+Xe[t&63]}function th(t,e,n){var i;var r=[];for(var o=e;o<n;o+=3){i=(t[o]<<16&16711680)+(t[o+1]<<8&65280)+(t[o+2]&255);r.push(eh(i))}return r.join("")}function nh(t){var e;var n=t.length;var i=n%3;var r=[];var o=16383;for(var l=0,u=n-i;l<u;l+=o){r.push(th(t,l,l+o>u?u:l+o))}if(i===1){e=t[n-1];r.push(Xe[e>>2]+Xe[e<<4&63]+"==")}else if(i===2){e=(t[n-2]<<8)+t[n-1];r.push(Xe[e>>10]+Xe[e>>4&63]+Xe[e<<2&63]+"=")}return r.join("")}});var Br=F(Vr=>{"use strict";Object.defineProperty(Vr,"__esModule",{value:true});Vr.fromArrayBufferToHex=ih;function ih(t){const e=Array.from(new Uint8Array(t));return e.map(n=>{return n.toString(16).padStart(2,"0")}).join("")}});var Yl=F(Vn=>{"use strict";Object.defineProperty(Vn,"__esModule",{value:true});Vn.BrowserCrypto=void 0;var Lt=Wl();var rh=Br();var $r=class t{constructor(){if(typeof window==="undefined"||window.crypto===void 0||window.crypto.subtle===void 0){throw new Error("SubtleCrypto not found. Make sure it's an https:// website.")}}async sha256DigestBase64(e){const n=new TextEncoder().encode(e);const i=await window.crypto.subtle.digest("SHA-256",n);return Lt.fromByteArray(new Uint8Array(i))}randomBytesBase64(e){const n=new Uint8Array(e);window.crypto.getRandomValues(n);return Lt.fromByteArray(n)}static padBase64(e){while(e.length%4!==0){e+="="}return e}async verify(e,n,i){const r={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};const o=new TextEncoder().encode(n);const l=Lt.toByteArray(t.padBase64(i));const u=await window.crypto.subtle.importKey("jwk",e,r,true,["verify"]);const c=await window.crypto.subtle.verify(r,u,Buffer.from(l),o);return c}async sign(e,n){const i={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};const r=new TextEncoder().encode(n);const o=await window.crypto.subtle.importKey("jwk",e,i,true,["sign"]);const l=await window.crypto.subtle.sign(i,o,r);return Lt.fromByteArray(new Uint8Array(l))}decodeBase64StringUtf8(e){const n=Lt.toByteArray(t.padBase64(e));const i=new TextDecoder().decode(n);return i}encodeBase64StringUtf8(e){const n=new TextEncoder().encode(e);const i=Lt.fromByteArray(n);return i}async sha256DigestHex(e){const n=new TextEncoder().encode(e);const i=await window.crypto.subtle.digest("SHA-256",n);return(0,rh.fromArrayBufferToHex)(i)}async signWithHmacSha256(e,n){const i=typeof e==="string"?e:String.fromCharCode(...new Uint16Array(e));const r=new TextEncoder;const o=await window.crypto.subtle.importKey("raw",r.encode(i),{name:"HMAC",hash:{name:"SHA-256"}},false,["sign"]);return window.crypto.subtle.sign("HMAC",o,r.encode(n))}};Vn.BrowserCrypto=$r});var zl=F(Bn=>{"use strict";Object.defineProperty(Bn,"__esModule",{value:true});Bn.NodeCrypto=void 0;var Gt=z("crypto");var Jr=class{async sha256DigestBase64(e){return Gt.createHash("sha256").update(e).digest("base64")}randomBytesBase64(e){return Gt.randomBytes(e).toString("base64")}async verify(e,n,i){const r=Gt.createVerify("RSA-SHA256");r.update(n);r.end();return r.verify(e,i,"base64")}async sign(e,n){const i=Gt.createSign("RSA-SHA256");i.update(n);i.end();return i.sign(e,"base64")}decodeBase64StringUtf8(e){return Buffer.from(e,"base64").toString("utf-8")}encodeBase64StringUtf8(e){return Buffer.from(e,"utf-8").toString("base64")}async sha256DigestHex(e){return Gt.createHash("sha256").update(e).digest("hex")}async signWithHmacSha256(e,n){const i=typeof e==="string"?e:sh(e);return oh(Gt.createHmac("sha256",i).update(n).digest())}};Bn.NodeCrypto=Jr;function oh(t){const e=new ArrayBuffer(t.length);const n=new Uint8Array(e);for(let i=0;i<t.length;++i){n[i]=t[i]}return e}function sh(t){return Buffer.from(t)}});var fn=F(it=>{"use strict";var ah=it&&it.__createBinding||(Object.create?(function(t,e,n,i){if(i===void 0)i=n;var r=Object.getOwnPropertyDescriptor(e,n);if(!r||("get"in r?!e.__esModule:r.writable||r.configurable)){r={enumerable:true,get:function(){return e[n]}}}Object.defineProperty(t,i,r)}):(function(t,e,n,i){if(i===void 0)i=n;t[i]=e[n]}));var lh=it&&it.__exportStar||function(t,e){for(var n in t)if(n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n))ah(e,t,n)};Object.defineProperty(it,"__esModule",{value:true});it.createCrypto=dh;it.hasBrowserCrypto=Xl;var uh=Yl();var ch=zl();lh(Br(),it);function dh(){if(Xl()){return new uh.BrowserCrypto}return new ch.NodeCrypto}function Xl(){return typeof window!=="undefined"&&typeof window.crypto!=="undefined"&&typeof window.crypto.subtle!=="undefined"}});var Zl=F((zS,Ql)=>{"use strict";function Kr(t){var e=(t/8|0)+(t%8===0?0:1);return e}var fh={ES256:Kr(256),ES384:Kr(384),ES512:Kr(521)};function ph(t){var e=fh[t];if(e){return e}throw new Error('Unknown algorithm "'+t+'"')}Ql.exports=ph});var Wr=F((XS,ru)=>{"use strict";var $n=an().Buffer;var eu=Zl();var Jn=128;var tu=0;var hh=32;var gh=16;var mh=2;var nu=gh|hh|tu<<6;var Kn=mh|tu<<6;function yh(t){return t.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function iu(t){if($n.isBuffer(t)){return t}else if("string"===typeof t){return $n.from(t,"base64")}throw new TypeError("ECDSA signature must be a Base64 string or a Buffer")}function Eh(t,e){t=iu(t);var n=eu(e);var i=n+1;var r=t.length;var o=0;if(t[o++]!==nu){throw new Error('Could not find expected "seq"')}var l=t[o++];if(l===(Jn|1)){l=t[o++]}if(r-o<l){throw new Error('"seq" specified length of "'+l+'", only "'+(r-o)+'" remaining')}if(t[o++]!==Kn){throw new Error('Could not find expected "int" for "r"')}var u=t[o++];if(r-o-2<u){throw new Error('"r" specified length of "'+u+'", only "'+(r-o-2)+'" available')}if(i<u){throw new Error('"r" specified length of "'+u+'", max of "'+i+'" is acceptable')}var c=o;o+=u;if(t[o++]!==Kn){throw new Error('Could not find expected "int" for "s"')}var d=t[o++];if(r-o!==d){throw new Error('"s" specified length of "'+d+'", expected "'+(r-o)+'"')}if(i<d){throw new Error('"s" specified length of "'+d+'", max of "'+i+'" is acceptable')}var f=o;o+=d;if(o!==r){throw new Error('Expected to consume entire buffer, but "'+(r-o)+'" bytes remain')}var p=n-u,h=n-d;var m=$n.allocUnsafe(p+u+h+d);for(o=0;o<p;++o){m[o]=0}t.copy(m,o,c+Math.max(-p,0),c+u);o=n;for(var _=o;o<_+h;++o){m[o]=0}t.copy(m,o,f+Math.max(-h,0),f+d);m=m.toString("base64");m=yh(m);return m}function jl(t,e,n){var i=0;while(e+i<n&&t[e+i]===0){++i}var r=t[e+i]>=Jn;if(r){--i}return i}function _h(t,e){t=iu(t);var n=eu(e);var i=t.length;if(i!==n*2){throw new TypeError('"'+e+'" signatures must be "'+n*2+'" bytes, saw "'+i+'"')}var r=jl(t,0,n);var o=jl(t,n,t.length);var l=n-r;var u=n-o;var c=1+1+l+1+1+u;var d=c<Jn;var f=$n.allocUnsafe((d?2:3)+c);var p=0;f[p++]=nu;if(d){f[p++]=c}else{f[p++]=Jn|1;f[p++]=c&255}f[p++]=Kn;f[p++]=l;if(r<0){f[p++]=0;p+=t.copy(f,p,0,n)}else{p+=t.copy(f,p,r,n)}f[p++]=Kn;f[p++]=u;if(o<0){f[p++]=0;t.copy(f,p,n)}else{t.copy(f,p,n+o)}return f}ru.exports={derToJose:Eh,joseToDer:_h}});var qe=F(rt=>{"use strict";Object.defineProperty(rt,"__esModule",{value:true});rt.LRUCache=void 0;rt.snakeToCamel=su;rt.originalOrCamelOptions=vh;rt.removeUndefinedValuesInObject=Sh;rt.isValidFile=Ih;rt.getWellKnownCertificateConfigFileLocation=wh;var Th=z("fs");var Ah=z("os");var Yr=z("path");var Ch="certificate_config.json";var ou="gcloud";function su(t){return t.replace(/([_][^_])/g,e=>e.slice(1).toUpperCase())}function vh(t){function e(n){const i=t||{};return i[n]??i[su(n)]}return{get:e}}var zr=class{capacity;#e=new Map;maxAge;constructor(e){this.capacity=e.capacity;this.maxAge=e.maxAge}#t(e,n){this.#e.delete(e);this.#e.set(e,{value:n,lastAccessed:Date.now()})}set(e,n){this.#t(e,n);this.#n()}get(e){const n=this.#e.get(e);if(!n)return;this.#t(e,n.value);this.#n();return n.value}#n(){const e=this.maxAge?Date.now()-this.maxAge:0;let n=this.#e.entries().next();while(!n.done&&(this.#e.size>this.capacity||n.value[1].lastAccessed<e)){this.#e.delete(n.value[0]);n=this.#e.entries().next()}}};rt.LRUCache=zr;function Sh(t){Object.entries(t).forEach(([e,n])=>{if(n===void 0||n==="undefined"){delete t[e]}});return t}async function Ih(t){try{const e=await Th.promises.lstat(t);return e.isFile()}catch(e){return false}}function wh(){const t=process.env.CLOUDSDK_CONFIG||(Rh()?Yr.join(process.env.APPDATA||"",ou):Yr.join(process.env.HOME||"",".config",ou));return Yr.join(t,Ch)}function Rh(){return Ah.platform().startsWith("win")}});var au=F((ZS,Ph)=>{Ph.exports={name:"google-auth-library",version:"10.9.1",author:"Google Inc.",description:"Google APIs Authentication Client Library for Node.js",engines:{node:">=18"},main:"./build/src/index.js",types:"./build/src/index.d.ts",repository:{type:"git",directory:"core/packages/google-auth-library-nodejs",url:"https://github.com/googleapis/google-cloud-node.git"},keywords:["google","api","google apis","client","client library"],dependencies:{"base64-js":"^1.3.0","ecdsa-sig-formatter":"^1.0.11",gaxios:"^7.1.4","gcp-metadata":"8.1.2","google-logging-utils":"1.1.3",jws:"^4.0.0"},devDependencies:{"@types/base64-js":"^1.2.5","@types/jws":"^3.1.0","@types/mocha":"^10.0.10","@types/mv":"^2.1.0","@types/ncp":"^2.0.8","@types/node":"^24.0.0","@types/sinon":"^21.0.0","assert-rejects":"^1.0.0",c8:"^10.1.3",codecov:"^3.8.3",gts:"^6.0.2","is-docker":"^3.0.0",jsdoc:"^4.0.4","jsdoc-fresh":"^5.0.0","jsdoc-region-tag":"^4.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.1",keypair:"^1.0.4",mocha:"^11.1.0",mv:"^2.1.1",ncp:"^2.0.0",nock:"^14.0.5","null-loader":"^4.0.1",puppeteer:"^24.0.0",sinon:"21.0.3","ts-loader":"^9.5.2",typescript:"5.8.3",webpack:"^5.97.1","webpack-cli":"^6.0.1"},files:["build/src","!build/src/**/*.map"],scripts:{test:"c8 mocha build/test",clean:"gts clean",prepare:"npm run compile",lint:"gts check --no-inline-config",compile:"tsc -p .",fix:"gts fix",pretest:"npm run compile -- --sourceMap",docs:"jsdoc -c .jsdoc.js","samples-setup":"cd samples/ && npm link ../ && npm run setup && cd ../","samples-test":"cd samples/ && npm link ../ && npm test && cd ../","system-test":"mocha build/system-test --timeout 60000","presystem-test":"npm run compile -- --sourceMap",webpack:"webpack","browser-test":"karma start",prelint:"cd samples; npm link ../; npm install"},license:"Apache-2.0",homepage:"https://github.com/googleapis/google-cloud-node/tree/main/core/packages/google-auth-library-nodejs"}});var Xr=F(ut=>{"use strict";Object.defineProperty(ut,"__esModule",{value:true});ut.USER_AGENT=ut.PRODUCT_NAME=ut.pkg=void 0;var lu=au();ut.pkg=lu;var uu="google-api-nodejs-client";ut.PRODUCT_NAME=uu;var Nh=`${uu}/${lu.version}`;ut.USER_AGENT=Nh});var Pe=F(He=>{"use strict";Object.defineProperty(He,"__esModule",{value:true});He.AuthClient=He.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=He.DEFAULT_UNIVERSE=void 0;var Mh=z("events");var Qr=ge();var kh=qe();var xh=Or();var Zr=Xr();He.DEFAULT_UNIVERSE="googleapis.com";He.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=5*60*1e3;var jr=class t extends Mh.EventEmitter{apiKey;projectId;quotaProjectId;transporter;credentials={};eagerRefreshThresholdMillis=He.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS;forceRefreshOnFailure=false;universeDomain=He.DEFAULT_UNIVERSE;static RequestMethodNameSymbol=Symbol("request method name");static RequestLogIdSymbol=Symbol("request log id");constructor(e={}){super();const n=(0,kh.originalOrCamelOptions)(e);this.apiKey=e.apiKey;this.projectId=n.get("project_id")??null;this.quotaProjectId=n.get("quota_project_id");this.credentials=n.get("credentials")??{};this.universeDomain=n.get("universe_domain")??He.DEFAULT_UNIVERSE;this.transporter=e.transporter??new Qr.Gaxios(e.transporterOptions);if(n.get("useAuthRequestParameters")!==false){this.transporter.interceptors.request.add(t.DEFAULT_REQUEST_INTERCEPTOR);this.transporter.interceptors.response.add(t.DEFAULT_RESPONSE_INTERCEPTOR)}if(e.eagerRefreshThresholdMillis){this.eagerRefreshThresholdMillis=e.eagerRefreshThresholdMillis}this.forceRefreshOnFailure=e.forceRefreshOnFailure??false}fetch(...e){const n=e[0];const i=e[1];let r=void 0;const o=new Headers;if(typeof n==="string"){r=new URL(n)}else if(n instanceof URL){r=n}else if(n&&n.url){r=new URL(n.url)}if(n&&typeof n==="object"&&"headers"in n){Qr.Gaxios.mergeHeaders(o,n.headers)}if(i){Qr.Gaxios.mergeHeaders(o,new Headers(i.headers))}if(typeof n==="object"&&!(n instanceof URL)){return this.request({...i,...n,headers:o,url:r})}else{return this.request({...i,headers:o,url:r})}}setCredentials(e){this.credentials=e}addSharedMetadataHeaders(e){if(!e.has("x-goog-user-project")&&this.quotaProjectId){e.set("x-goog-user-project",this.quotaProjectId)}return e}addUserProjectAndAuthHeaders(e,n){const i=n.get("x-goog-user-project");const r=n.get("authorization");if(i){e.set("x-goog-user-project",i)}if(r){e.set("authorization",r)}return e}static log=(0,xh.log)("auth");static DEFAULT_REQUEST_INTERCEPTOR={resolved:async e=>{if(!e.headers.has("x-goog-api-client")){const i=process.version.replace(/^v/,"");e.headers.set("x-goog-api-client",`gl-node/${i}`)}const n=e.headers.get("User-Agent");if(!n){e.headers.set("User-Agent",Zr.USER_AGENT)}else if(!n.includes(`${Zr.PRODUCT_NAME}/`)){e.headers.set("User-Agent",`${n} ${Zr.USER_AGENT}`)}try{const i=e;const r=i[t.RequestMethodNameSymbol];const o=`${Math.floor(Math.random()*1e3)}`;i[t.RequestLogIdSymbol]=o;const l={url:e.url,headers:e.headers};if(r){t.log.info("%s [%s] request %j",r,o,l)}else{t.log.info("[%s] request %j",o,l)}}catch(i){}return e}};static DEFAULT_RESPONSE_INTERCEPTOR={resolved:async e=>{try{const n=e.config;const i=n[t.RequestMethodNameSymbol];const r=n[t.RequestLogIdSymbol];if(i){t.log.info("%s [%s] response %j",i,r,e.data)}else{t.log.info("[%s] response %j",r,e.data)}}catch(n){}return e},rejected:async e=>{try{const n=e.config;const i=n[t.RequestMethodNameSymbol];const r=n[t.RequestLogIdSymbol];if(i){t.log.info("%s [%s] error %j",i,r,e.response?.data)}else{t.log.error("[%s] error %j",r,e.response?.data)}}catch(n){}throw e}};static setMethodName(e,n){try{const i=e;i[t.RequestMethodNameSymbol]=n}catch(i){}}static get RETRY_CONFIG(){return{retry:true,retryConfig:{httpMethodsToRetry:["GET","PUT","POST","HEAD","OPTIONS","DELETE"]}}}};He.AuthClient=jr});var to=F(Wn=>{"use strict";Object.defineProperty(Wn,"__esModule",{value:true});Wn.LoginTicket=void 0;var eo=class{envelope;payload;constructor(e,n){this.envelope=e;this.payload=n}getEnvelope(){return this.envelope}getPayload(){return this.payload}getUserId(){const e=this.getPayload();if(e&&e.sub){return e.sub}return null}getAttributes(){return{envelope:this.getEnvelope(),payload:this.getPayload()}}};Wn.LoginTicket=eo});var ct=F(Qe=>{"use strict";Object.defineProperty(Qe,"__esModule",{value:true});Qe.OAuth2Client=Qe.ClientAuthentication=Qe.CertificateFormat=Qe.CodeChallengeMethod=void 0;var cu=ge();var Dh=z("querystring");var Uh=z("stream");var Lh=Wr();var du=qe();var no=fn();var Ot=Pe();var Gh=to();var fu;(function(t){t["Plain"]="plain";t["S256"]="S256"})(fu||(Qe.CodeChallengeMethod=fu={}));var ot;(function(t){t["PEM"]="PEM";t["JWK"]="JWK"})(ot||(Qe.CertificateFormat=ot={}));var pn;(function(t){t["ClientSecretPost"]="ClientSecretPost";t["ClientSecretBasic"]="ClientSecretBasic";t["None"]="None"})(pn||(Qe.ClientAuthentication=pn={}));var io=class t extends Ot.AuthClient{redirectUri;certificateCache={};certificateExpiry=null;certificateCacheFormat=ot.PEM;refreshTokenPromises=new Map;endpoints;issuers;clientAuthentication;_clientId;_clientSecret;refreshHandler;constructor(e={},n,i){super(typeof e==="object"?e:{});if(typeof e!=="object"){e={clientId:e,clientSecret:n,redirectUri:i}}this._clientId=e.clientId||e.client_id;this._clientSecret=e.clientSecret||e.client_secret;this.redirectUri=e.redirectUri||e.redirect_uris?.[0];this.endpoints={tokenInfoUrl:"https://oauth2.googleapis.com/tokeninfo",oauth2AuthBaseUrl:"https://accounts.google.com/o/oauth2/v2/auth",oauth2TokenUrl:"https://oauth2.googleapis.com/token",oauth2RevokeUrl:"https://oauth2.googleapis.com/revoke",oauth2FederatedSignonPemCertsUrl:"https://www.googleapis.com/oauth2/v1/certs",oauth2FederatedSignonJwkCertsUrl:"https://www.googleapis.com/oauth2/v3/certs",oauth2IapPublicKeyUrl:"https://www.gstatic.com/iap/verify/public_key",...e.endpoints};this.clientAuthentication=e.clientAuthentication||pn.ClientSecretPost;this.issuers=e.issuers||["accounts.google.com","https://accounts.google.com",this.universeDomain]}static GOOGLE_TOKEN_INFO_URL="https://oauth2.googleapis.com/tokeninfo";static CLOCK_SKEW_SECS_=300;static DEFAULT_MAX_TOKEN_LIFETIME_SECS_=86400;generateAuthUrl(e={}){if(e.code_challenge_method&&!e.code_challenge){throw new Error("If a code_challenge_method is provided, code_challenge must be included.")}e.response_type=e.response_type||"code";e.client_id=e.client_id||this._clientId;e.redirect_uri=e.redirect_uri||this.redirectUri;if(Array.isArray(e.scope)){e.scope=e.scope.join(" ")}const n=this.endpoints.oauth2AuthBaseUrl.toString();return n+"?"+Dh.stringify(e)}generateCodeVerifier(){throw new Error("generateCodeVerifier is removed, please use generateCodeVerifierAsync instead.")}async generateCodeVerifierAsync(){const e=(0,no.createCrypto)();const n=e.randomBytesBase64(96);const i=n.replace(/\+/g,"~").replace(/=/g,"_").replace(/\//g,"-");const r=await e.sha256DigestBase64(i);const o=r.split("=")[0].replace(/\+/g,"-").replace(/\//g,"_");return{codeVerifier:i,codeChallenge:o}}getToken(e,n){const i=typeof e==="string"?{code:e}:e;if(n){this.getTokenAsync(i).then(r=>n(null,r.tokens,r.res),r=>n(r,null,r.response))}else{return this.getTokenAsync(i)}}async getTokenAsync(e){const n=this.endpoints.oauth2TokenUrl.toString();const i=new Headers;const r={client_id:e.client_id||this._clientId,code_verifier:e.codeVerifier,code:e.code,grant_type:"authorization_code",redirect_uri:e.redirect_uri||this.redirectUri};if(this.clientAuthentication===pn.ClientSecretBasic){const c=Buffer.from(`${this._clientId}:${this._clientSecret}`);i.set("authorization",`Basic ${c.toString("base64")}`)}if(this.clientAuthentication===pn.ClientSecretPost){r.client_secret=this._clientSecret}const o={...t.RETRY_CONFIG,method:"POST",url:n,data:new URLSearchParams((0,du.removeUndefinedValuesInObject)(r)),headers:i};Ot.AuthClient.setMethodName(o,"getTokenAsync");const l=await this.transporter.request(o);const u=l.data;if(l.data&&l.data.expires_in){u.expiry_date=new Date().getTime()+l.data.expires_in*1e3;delete u.expires_in}this.emit("tokens",u);return{tokens:u,res:l}}async refreshToken(e){if(!e){return this.refreshTokenNoCache(e)}if(this.refreshTokenPromises.has(e)){return this.refreshTokenPromises.get(e)}const n=this.refreshTokenNoCache(e).then(i=>{this.refreshTokenPromises.delete(e);return i},i=>{this.refreshTokenPromises.delete(e);throw i});this.refreshTokenPromises.set(e,n);return n}async refreshTokenNoCache(e){if(!e){throw new Error("No refresh token is set.")}const n=this.endpoints.oauth2TokenUrl.toString();const i={refresh_token:e,client_id:this._clientId,client_secret:this._clientSecret,grant_type:"refresh_token"};let r;try{const l={...t.RETRY_CONFIG,method:"POST",url:n,data:new URLSearchParams((0,du.removeUndefinedValuesInObject)(i))};Ot.AuthClient.setMethodName(l,"refreshTokenNoCache");r=await this.transporter.request(l)}catch(l){if(l instanceof cu.GaxiosError&&l.message==="invalid_grant"&&l.response?.data&&/ReAuth/i.test(l.response.data.error_description)){l.message=JSON.stringify(l.response.data)}throw l}const o=r.data;if(r.data&&r.data.expires_in){o.expiry_date=new Date().getTime()+r.data.expires_in*1e3;delete o.expires_in}this.emit("tokens",o);return{tokens:o,res:r}}refreshAccessToken(e){if(e){this.refreshAccessTokenAsync().then(n=>e(null,n.credentials,n.res),e)}else{return this.refreshAccessTokenAsync()}}async refreshAccessTokenAsync(){const e=await this.refreshToken(this.credentials.refresh_token);const n=e.tokens;n.refresh_token=this.credentials.refresh_token;this.credentials=n;return{credentials:this.credentials,res:e.res}}getAccessToken(e){if(e){this.getAccessTokenAsync().then(n=>e(null,n.token,n.res),e)}else{return this.getAccessTokenAsync()}}async getAccessTokenAsync(){const e=!this.credentials.access_token||this.isTokenExpiring();if(e){if(!this.credentials.refresh_token){if(this.refreshHandler){const i=await this.processAndValidateRefreshHandler();if(i?.access_token){this.setCredentials(i);return{token:this.credentials.access_token}}}else{throw new Error("No refresh token or refresh handler callback is set.")}}const n=await this.refreshAccessTokenAsync();if(!n.credentials||n.credentials&&!n.credentials.access_token){throw new Error("Could not refresh access token.")}return{token:n.credentials.access_token,res:n.res}}else{return{token:this.credentials.access_token}}}async getRequestHeaders(e){const n=(await this.getRequestMetadataAsync(e)).headers;return n}async getRequestMetadataAsync(e){e;const n=this.credentials;if(!n.access_token&&!n.refresh_token&&!this.apiKey&&!this.refreshHandler){throw new Error("No access, refresh token, API key or refresh handler callback is set.")}if(n.access_token&&!this.isTokenExpiring()){n.token_type=n.token_type||"Bearer";const u=new Headers({authorization:n.token_type+" "+n.access_token});return{headers:this.addSharedMetadataHeaders(u)}}if(this.refreshHandler){const u=await this.processAndValidateRefreshHandler();if(u?.access_token){this.setCredentials(u);const c=new Headers({authorization:"Bearer "+this.credentials.access_token});return{headers:this.addSharedMetadataHeaders(c)}}}if(this.apiKey){return{headers:new Headers({"X-Goog-Api-Key":this.apiKey})}}let i=null;let r=null;try{i=await this.refreshToken(n.refresh_token);r=i.tokens}catch(u){const c=u;if(c.response&&(c.response.status===403||c.response.status===404)){c.message=`Could not refresh access token: ${c.message}`}throw c}const o=this.credentials;o.token_type=o.token_type||"Bearer";r.refresh_token=o.refresh_token;this.credentials=r;const l=new Headers({authorization:o.token_type+" "+r.access_token});return{headers:this.addSharedMetadataHeaders(l),res:i.res}}static getRevokeTokenUrl(e){return new t().getRevokeTokenURL(e).toString()}getRevokeTokenURL(e){const n=new URL(this.endpoints.oauth2RevokeUrl);n.searchParams.append("token",e);return n}revokeToken(e,n){const i={...t.RETRY_CONFIG,url:this.getRevokeTokenURL(e).toString(),method:"POST"};Ot.AuthClient.setMethodName(i,"revokeToken");if(n){this.transporter.request(i).then(r=>n(null,r),n)}else{return this.transporter.request(i)}}revokeCredentials(e){if(e){this.revokeCredentialsAsync().then(n=>e(null,n),e)}else{return this.revokeCredentialsAsync()}}async revokeCredentialsAsync(){const e=this.credentials.access_token;this.credentials={};if(e){return this.revokeToken(e)}else{throw new Error("No access token to revoke.")}}request(e,n){if(n){this.requestAsync(e).then(i=>n(null,i),i=>{return n(i,i.response)})}else{return this.requestAsync(e)}}async requestAsync(e,n=false){try{const i=await this.getRequestMetadataAsync();e.headers=cu.Gaxios.mergeHeaders(e.headers);this.addUserProjectAndAuthHeaders(e.headers,i.headers);if(this.apiKey){e.headers.set("X-Goog-Api-Key",this.apiKey)}return await this.transporter.request(e)}catch(i){const r=i.response;if(r){const o=r.status;const l=this.credentials&&this.credentials.access_token&&this.credentials.refresh_token&&(!this.credentials.expiry_date||this.forceRefreshOnFailure);const u=this.credentials&&this.credentials.access_token&&!this.credentials.refresh_token&&(!this.credentials.expiry_date||this.forceRefreshOnFailure)&&this.refreshHandler;const c=r.config.data instanceof Uh.Readable;const d=o===401||o===403;if(!n&&d&&!c&&l){await this.refreshAccessTokenAsync();return this.requestAsync(e,true)}else if(!n&&d&&!c&&u){const f=await this.processAndValidateRefreshHandler();if(f?.access_token){this.setCredentials(f)}return this.requestAsync(e,true)}}throw i}}verifyIdToken(e,n){if(n&&typeof n!=="function"){throw new Error("This method accepts an options object as the first parameter, which includes the idToken, audience, and maxExpiry.")}if(n){this.verifyIdTokenAsync(e).then(i=>n(null,i),n)}else{return this.verifyIdTokenAsync(e)}}async verifyIdTokenAsync(e){if(!e.idToken){throw new Error("The verifyIdToken method requires an ID Token")}const n=await this.getFederatedSignonCertsAsync();const i=await this.verifySignedJwtWithCertsAsync(e.idToken,n.certs,e.audience,this.issuers,e.maxExpiry);return i}async getTokenInfo(e){const{data:n}=await this.transporter.request({...t.RETRY_CONFIG,method:"POST",headers:{"content-type":"application/x-www-form-urlencoded;charset=UTF-8",authorization:`Bearer ${e}`},url:this.endpoints.tokenInfoUrl.toString()});const i=Object.assign({expiry_date:new Date().getTime()+n.expires_in*1e3,scopes:n.scope.split(" ")},n);delete i.expires_in;delete i.scope;return i}getFederatedSignonCerts(e){if(e){this.getFederatedSignonCertsAsync().then(n=>e(null,n.certs,n.res),e)}else{return this.getFederatedSignonCertsAsync()}}async getFederatedSignonCertsAsync(){const e=new Date().getTime();const n=(0,no.hasBrowserCrypto)()?ot.JWK:ot.PEM;if(this.certificateExpiry&&e<this.certificateExpiry.getTime()&&this.certificateCacheFormat===n){return{certs:this.certificateCache,format:n}}let i;let r;switch(n){case ot.PEM:r=this.endpoints.oauth2FederatedSignonPemCertsUrl.toString();break;case ot.JWK:r=this.endpoints.oauth2FederatedSignonJwkCertsUrl.toString();break;default:throw new Error(`Unsupported certificate format ${n}`)}try{const d={...t.RETRY_CONFIG,url:r};Ot.AuthClient.setMethodName(d,"getFederatedSignonCertsAsync");i=await this.transporter.request(d)}catch(d){if(d instanceof Error){d.message=`Failed to retrieve verification certificates: ${d.message}`}throw d}const o=i?.headers.get("cache-control");let l=-1;if(o){const d=/max-age=(?<maxAge>[0-9]+)/.exec(o)?.groups?.maxAge;if(d){l=Number(d)*1e3}}let u={};switch(n){case ot.PEM:u=i.data;break;case ot.JWK:for(const d of i.data.keys){u[d.kid]=d}break;default:throw new Error(`Unsupported certificate format ${n}`)}const c=new Date;this.certificateExpiry=l===-1?null:new Date(c.getTime()+l);this.certificateCache=u;this.certificateCacheFormat=n;return{certs:u,format:n,res:i}}getIapPublicKeys(e){if(e){this.getIapPublicKeysAsync().then(n=>e(null,n.pubkeys,n.res),e)}else{return this.getIapPublicKeysAsync()}}async getIapPublicKeysAsync(){let e;const n=this.endpoints.oauth2IapPublicKeyUrl.toString();try{const i={...t.RETRY_CONFIG,url:n};Ot.AuthClient.setMethodName(i,"getIapPublicKeysAsync");e=await this.transporter.request(i)}catch(i){if(i instanceof Error){i.message=`Failed to retrieve verification certificates: ${i.message}`}throw i}return{pubkeys:e.data,res:e}}verifySignedJwtWithCerts(){throw new Error("verifySignedJwtWithCerts is removed, please use verifySignedJwtWithCertsAsync instead.")}async verifySignedJwtWithCertsAsync(e,n,i,r,o){const l=(0,no.createCrypto)();if(!o){o=t.DEFAULT_MAX_TOKEN_LIFETIME_SECS_}const u=e.split(".");if(u.length!==3){throw new Error("Wrong number of segments in token: "+e)}const c=u[0]+"."+u[1];let d=u[2];let f;let p;try{f=JSON.parse(l.decodeBase64StringUtf8(u[0]))}catch(D){if(D instanceof Error){D.message=`Can't parse token envelope: ${u[0]}': ${D.message}`}throw D}if(!f){throw new Error("Can't parse token envelope: "+u[0])}try{p=JSON.parse(l.decodeBase64StringUtf8(u[1]))}catch(D){if(D instanceof Error){D.message=`Can't parse token payload '${u[0]}`}throw D}if(!p){throw new Error("Can't parse token payload: "+u[1])}if(!Object.prototype.hasOwnProperty.call(n,f.kid)){throw new Error("No pem found for envelope: "+JSON.stringify(f))}const h=n[f.kid];if(f.alg==="ES256"){d=Lh.joseToDer(d,"ES256").toString("base64")}const m=await l.verify(h,c,d);if(!m){throw new Error("Invalid token signature: "+e)}if(!p.iat){throw new Error("No issue time in token: "+JSON.stringify(p))}if(!p.exp){throw new Error("No expiration time in token: "+JSON.stringify(p))}const _=Number(p.iat);if(isNaN(_))throw new Error("iat field using invalid format");const A=Number(p.exp);if(isNaN(A))throw new Error("exp field using invalid format");const T=new Date().getTime()/1e3;if(A>=T+o){throw new Error("Expiration time too far in future: "+JSON.stringify(p))}const v=_-t.CLOCK_SKEW_SECS_;const G=A+t.CLOCK_SKEW_SECS_;if(T<v){throw new Error("Token used too early, "+T+" < "+v+": "+JSON.stringify(p))}if(T>G){throw new Error("Token used too late, "+T+" > "+G+": "+JSON.stringify(p))}if(r&&r.indexOf(p.iss)<0){throw new Error("Invalid issuer, expected one of ["+r+"], but got "+p.iss)}if(typeof i!=="undefined"&&i!==null){const D=p.aud;let O=false;if(i.constructor===Array){O=i.indexOf(D)>-1}else{O=D===i}if(!O){throw new Error("Wrong recipient, payload audience != requiredAudience")}}return new Gh.LoginTicket(f,p)}async processAndValidateRefreshHandler(){if(this.refreshHandler){const e=await this.refreshHandler();if(!e.access_token){throw new Error("No access token is returned by the refreshHandler callback.")}return e}return}isTokenExpiring(){const e=this.credentials.expiry_date;return e?e<=new Date().getTime()+this.eagerRefreshThresholdMillis:false}};Qe.OAuth2Client=io});var oo=F(Yn=>{"use strict";Object.defineProperty(Yn,"__esModule",{value:true});Yn.Compute=void 0;var Oh=ge();var pu=dn();var bh=ct();var ro=class extends bh.OAuth2Client{serviceAccountEmail;scopes;constructor(e={}){super(e);this.credentials={expiry_date:1,refresh_token:"compute-placeholder"};this.serviceAccountEmail=e.serviceAccountEmail||"default";this.scopes=Array.isArray(e.scopes)?e.scopes:e.scopes?[e.scopes]:[]}async refreshTokenNoCache(){const e=`service-accounts/${this.serviceAccountEmail}/token`;let n;try{const r={property:e};if(this.scopes.length>0){r.params={scopes:this.scopes.join(",")}}n=await pu.instance(r)}catch(r){if(r instanceof Oh.GaxiosError){r.message=`Could not refresh access token: ${r.message}`;this.wrapError(r)}throw r}const i=n;if(n&&n.expires_in){i.expiry_date=new Date().getTime()+n.expires_in*1e3;delete i.expires_in}this.emit("tokens",i);return{tokens:i,res:null}}async fetchIdToken(e){const n=`service-accounts/${this.serviceAccountEmail}/identity?format=full&audience=${e}`;let i;try{const r={property:n};i=await pu.instance(r)}catch(r){if(r instanceof Error){r.message=`Could not fetch ID token: ${r.message}`}throw r}return i}wrapError(e){const n=e.response;if(n&&n.status){e.status=n.status;if(n.status===403){e.message="A Forbidden error was returned while attempting to retrieve an access token for the Compute Engine built-in service account. This may be because the Compute Engine instance does not have the correct permission scopes specified: "+e.message}else if(n.status===404){e.message="A Not Found error was returned while attempting to retrieve an accesstoken for the Compute Engine built-in service account. This may be because the Compute Engine instance does not have any permission scopes specified: "+e.message}}}};Yn.Compute=ro});var ao=F(zn=>{"use strict";Object.defineProperty(zn,"__esModule",{value:true});zn.IdTokenClient=void 0;var Fh=ct();var so=class extends Fh.OAuth2Client{targetAudience;idTokenProvider;constructor(e){super(e);this.targetAudience=e.targetAudience;this.idTokenProvider=e.idTokenProvider}async getRequestMetadataAsync(){if(!this.credentials.id_token||!this.credentials.expiry_date||this.isTokenExpiring()){const n=await this.idTokenProvider.fetchIdToken(this.targetAudience);this.credentials={id_token:n,expiry_date:this.getIdTokenExpiryDate(n)}}const e=new Headers({authorization:"Bearer "+this.credentials.id_token});return{headers:e}}getIdTokenExpiryDate(e){const n=e.split(".")[1];if(n){const i=JSON.parse(Buffer.from(n,"base64").toString("ascii"));return i.exp*1e3}}};zn.IdTokenClient=so});var lo=F(bt=>{"use strict";Object.defineProperty(bt,"__esModule",{value:true});bt.GCPEnv=void 0;bt.clear=qh;bt.getEnv=Hh;var hu=dn();var Ze;(function(t){t["APP_ENGINE"]="APP_ENGINE";t["KUBERNETES_ENGINE"]="KUBERNETES_ENGINE";t["CLOUD_FUNCTIONS"]="CLOUD_FUNCTIONS";t["COMPUTE_ENGINE"]="COMPUTE_ENGINE";t["CLOUD_RUN"]="CLOUD_RUN";t["CLOUD_RUN_JOBS"]="CLOUD_RUN_JOBS";t["NONE"]="NONE"})(Ze||(bt.GCPEnv=Ze={}));var hn;function qh(){hn=void 0}async function Hh(){if(hn){return hn}hn=Vh();return hn}async function Vh(){let t=Ze.NONE;if(Bh()){t=Ze.APP_ENGINE}else if($h()){t=Ze.CLOUD_FUNCTIONS}else if(await Yh()){if(await Wh()){t=Ze.KUBERNETES_ENGINE}else if(Jh()){t=Ze.CLOUD_RUN}else if(Kh()){t=Ze.CLOUD_RUN_JOBS}else{t=Ze.COMPUTE_ENGINE}}else{t=Ze.NONE}return t}function Bh(){return!!(process.env.GAE_SERVICE||process.env.GAE_MODULE_NAME)}function $h(){return!!(process.env.FUNCTION_NAME||process.env.FUNCTION_TARGET)}function Jh(){return!!process.env.K_CONFIGURATION}function Kh(){return!!process.env.CLOUD_RUN_JOB}async function Wh(){try{await hu.instance("attributes/cluster-name");return true}catch(t){return false}}async function Yh(){return hu.isAvailable()}});var uo=F((sI,gu)=>{var Xn=an().Buffer;var zh=z("stream");var Xh=z("util");function Qn(t){this.buffer=null;this.writable=true;this.readable=true;if(!t){this.buffer=Xn.alloc(0);return this}if(typeof t.pipe==="function"){this.buffer=Xn.alloc(0);t.pipe(this);return this}if(t.length||typeof t==="object"){this.buffer=t;this.writable=false;process.nextTick(function(){this.emit("end",t);this.readable=false;this.emit("close")}.bind(this));return this}throw new TypeError("Unexpected data type ("+typeof t+")")}Xh.inherits(Qn,zh);Qn.prototype.write=function t(e){this.buffer=Xn.concat([this.buffer,Xn.from(e)]);this.emit("data",e)};Qn.prototype.end=function t(e){if(e)this.write(e);this.emit("end",e);this.emit("close");this.writable=false;this.readable=false};gu.exports=Qn});var yu=F((aI,mu)=>{"use strict";var gn=z("buffer").Buffer;var co=z("buffer").SlowBuffer;mu.exports=Zn;function Zn(t,e){if(!gn.isBuffer(t)||!gn.isBuffer(e)){return false}if(t.length!==e.length){return false}var n=0;for(var i=0;i<t.length;i++){n|=t[i]^e[i]}return n===0}Zn.install=function(){gn.prototype.equal=co.prototype.equal=function t(e){return Zn(this,e)}};var Qh=gn.prototype.equal;var Zh=co.prototype.equal;Zn.restore=function(){gn.prototype.equal=Qh;co.prototype.equal=Zh}});var go=F((lI,wu)=>{var qt=an().Buffer;var Le=z("crypto");var _u=Wr();var Eu=z("util");var jh='"%s" is not a valid algorithm.\n Supported algorithms are:\n "HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".';var mn="secret must be a string or buffer";var Ft="key must be a string or a buffer";var eg="key must be a string, a buffer or an object";var po=typeof Le.createPublicKey==="function";if(po){Ft+=" or a KeyObject";mn+="or a KeyObject"}function Tu(t){if(qt.isBuffer(t)){return}if(typeof t==="string"){return}if(!po){throw Ve(Ft)}if(typeof t!=="object"){throw Ve(Ft)}if(typeof t.type!=="string"){throw Ve(Ft)}if(typeof t.asymmetricKeyType!=="string"){throw Ve(Ft)}if(typeof t.export!=="function"){throw Ve(Ft)}}function Au(t){if(qt.isBuffer(t)){return}if(typeof t==="string"){return}if(typeof t==="object"){return}throw Ve(eg)}function tg(t){if(qt.isBuffer(t)){return}if(typeof t==="string"){return t}if(!po){throw Ve(mn)}if(typeof t!=="object"){throw Ve(mn)}if(t.type!=="secret"){throw Ve(mn)}if(typeof t.export!=="function"){throw Ve(mn)}}function ho(t){return t.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function Cu(t){t=t.toString();var e=4-t.length%4;if(e!==4){for(var n=0;n<e;++n){t+="="}}return t.replace(/\-/g,"+").replace(/_/g,"/")}function Ve(t){var e=[].slice.call(arguments,1);var n=Eu.format.bind(Eu,t).apply(null,e);return new TypeError(n)}function ng(t){return qt.isBuffer(t)||typeof t==="string"}function yn(t){if(!ng(t))t=JSON.stringify(t);return t}function vu(t){return function e(n,i){tg(i);n=yn(n);var r=Le.createHmac("sha"+t,i);var o=(r.update(n),r.digest("base64"));return ho(o)}}var fo;var ig="timingSafeEqual"in Le?function t(e,n){if(e.byteLength!==n.byteLength){return false}return Le.timingSafeEqual(e,n)}:function t(e,n){if(!fo){fo=yu()}return fo(e,n)};function rg(t){return function e(n,i,r){var o=vu(t)(n,r);return ig(qt.from(i),qt.from(o))}}function Su(t){return function e(n,i){Au(i);n=yn(n);var r=Le.createSign("RSA-SHA"+t);var o=(r.update(n),r.sign(i,"base64"));return ho(o)}}function Iu(t){return function e(n,i,r){Tu(r);n=yn(n);i=Cu(i);var o=Le.createVerify("RSA-SHA"+t);o.update(n);return o.verify(r,i,"base64")}}function og(t){return function e(n,i){Au(i);n=yn(n);var r=Le.createSign("RSA-SHA"+t);var o=(r.update(n),r.sign({key:i,padding:Le.constants.RSA_PKCS1_PSS_PADDING,saltLength:Le.constants.RSA_PSS_SALTLEN_DIGEST},"base64"));return ho(o)}}function sg(t){return function e(n,i,r){Tu(r);n=yn(n);i=Cu(i);var o=Le.createVerify("RSA-SHA"+t);o.update(n);return o.verify({key:r,padding:Le.constants.RSA_PKCS1_PSS_PADDING,saltLength:Le.constants.RSA_PSS_SALTLEN_DIGEST},i,"base64")}}function ag(t){var e=Su(t);return function n(){var i=e.apply(null,arguments);i=_u.derToJose(i,"ES"+t);return i}}function lg(t){var e=Iu(t);return function n(i,r,o){r=_u.joseToDer(r,"ES"+t).toString("base64");var l=e(i,r,o);return l}}function ug(){return function t(){return""}}function cg(){return function t(e,n){return n===""}}wu.exports=function t(e){var n={hs:vu,rs:Su,ps:og,es:ag,none:ug};var i={hs:rg,rs:Iu,ps:sg,es:lg,none:cg};var r=e.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/);if(!r)throw Ve(jh,e);var o=(r[1]||r[3]).toLowerCase();var l=r[2];return{sign:n[o](l),verify:i[o](l)}}});var mo=F((uI,Ru)=>{var dg=z("buffer").Buffer;Ru.exports=function t(e){if(typeof e==="string")return e;if(typeof e==="number"||dg.isBuffer(e))return e.toString();return JSON.stringify(e)}});var Du=F((cI,xu)=>{var fg=an().Buffer;var Pu=uo();var pg=go();var hg=z("stream");var Nu=mo();var yo=z("util");function Mu(t,e){return fg.from(t,e).toString("base64").replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function gg(t,e,n){n=n||"utf8";var i=Mu(Nu(t),"binary");var r=Mu(Nu(e),n);return yo.format("%s.%s",i,r)}function ku(t){var e=t.header;var n=t.payload;var i=t.secret||t.privateKey;var r=t.encoding;var o=pg(e.alg);var l=gg(e,n,r);var u=o.sign(l,i);return yo.format("%s.%s",l,u)}function jn(t){var e=t.secret;e=e==null?t.privateKey:e;e=e==null?t.key:e;if(/^hs/i.test(t.header.alg)===true&&e==null){throw new TypeError("secret must be a string or buffer or a KeyObject")}var n=new Pu(e);this.readable=true;this.header=t.header;this.encoding=t.encoding;this.secret=this.privateKey=this.key=n;this.payload=new Pu(t.payload);this.secret.once("close",function(){if(!this.payload.writable&&this.readable)this.sign()}.bind(this));this.payload.once("close",function(){if(!this.secret.writable&&this.readable)this.sign()}.bind(this))}yo.inherits(jn,hg);jn.prototype.sign=function t(){try{var e=ku({header:this.header,payload:this.payload.buffer,secret:this.secret.buffer,encoding:this.encoding});this.emit("done",e);this.emit("data",e);this.emit("end");this.readable=false;return e}catch(n){this.readable=false;this.emit("error",n);this.emit("close")}};jn.sign=ku;xu.exports=jn});var Bu=F((dI,Vu)=>{var Lu=an().Buffer;var Uu=uo();var mg=go();var yg=z("stream");var Gu=mo();var Eg=z("util");var _g=/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;function Tg(t){return Object.prototype.toString.call(t)==="[object Object]"}function Ag(t){if(Tg(t))return t;try{return JSON.parse(t)}catch(e){return void 0}}function Ou(t){var e=t.split(".",1)[0];return Ag(Lu.from(e,"base64").toString("binary"))}function Cg(t){return t.split(".",2).join(".")}function bu(t){return t.split(".")[2]}function vg(t,e){e=e||"utf8";var n=t.split(".")[1];return Lu.from(n,"base64").toString(e)}function Fu(t){return _g.test(t)&&!!Ou(t)}function qu(t,e,n){if(!e){var i=new Error("Missing algorithm parameter for jws.verify");i.code="MISSING_ALGORITHM";throw i}t=Gu(t);var r=bu(t);var o=Cg(t);var l=mg(e);return l.verify(o,r,n)}function Hu(t,e){e=e||{};t=Gu(t);if(!Fu(t))return null;var n=Ou(t);if(!n)return null;var i=vg(t);if(n.typ==="JWT"||e.json)i=JSON.parse(i,e.encoding);return{header:n,payload:i,signature:bu(t)}}function Ht(t){t=t||{};var e=t.secret;e=e==null?t.publicKey:e;e=e==null?t.key:e;if(/^hs/i.test(t.algorithm)===true&&e==null){throw new TypeError("secret must be a string or buffer or a KeyObject")}var n=new Uu(e);this.readable=true;this.algorithm=t.algorithm;this.encoding=t.encoding;this.secret=this.publicKey=this.key=n;this.signature=new Uu(t.signature);this.secret.once("close",function(){if(!this.signature.writable&&this.readable)this.verify()}.bind(this));this.signature.once("close",function(){if(!this.secret.writable&&this.readable)this.verify()}.bind(this))}Eg.inherits(Ht,yg);Ht.prototype.verify=function t(){try{var e=qu(this.signature.buffer,this.algorithm,this.key.buffer);var n=Hu(this.signature.buffer,this.encoding);this.emit("done",e,n);this.emit("data",e);this.emit("end");this.readable=false;return e}catch(i){this.readable=false;this.emit("error",i);this.emit("close")}};Ht.decode=Hu;Ht.isValid=Fu;Ht.verify=qu;Vu.exports=Ht});var Eo=F(dt=>{var $u=Du();var ei=Bu();var Sg=["HS256","HS384","HS512","RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512"];dt.ALGORITHMS=Sg;dt.sign=$u.sign;dt.verify=ei.verify;dt.decode=ei.decode;dt.isValid=ei.isValid;dt.createSign=function t(e){return new $u(e)};dt.createVerify=function t(e){return new ei(e)}});var Ku=F(ti=>{"use strict";Object.defineProperty(ti,"__esModule",{value:true});ti.buildPayloadForJwsSign=Ju;ti.getJwsSign=Pg;var Ig=Eo();var wg="RS256";var Rg="https://oauth2.googleapis.com/token";function Ju(t){const e=Math.floor(new Date().getTime()/1e3);const n={iss:t.iss,scope:t.scope,aud:Rg,exp:e+3600,iat:e,sub:t.sub,...t.additionalClaims};return n}function Pg(t){const e=Ju(t);return(0,Ig.sign)({header:{alg:wg},payload:e,secret:t.key})}});var Wu=F(_o=>{"use strict";Object.defineProperty(_o,"__esModule",{value:true});_o.getToken=Dg;var Ng=Ku();var Mg="https://oauth2.googleapis.com/token";var kg="urn:ietf:params:oauth:grant-type:jwt-bearer";var xg=t=>{return{method:"POST",url:Mg,data:new URLSearchParams({grant_type:kg,assertion:(0,Ng.getJwsSign)(t)}),responseType:"json",retryConfig:{httpMethodsToRetry:["POST"]}}};async function Dg(t){if(!t.transporter){throw new Error("No transporter set.")}try{const e=xg(t);const n=await t.transporter.request(e);return n.data}catch(e){const n=e;const i=n.response?.data;if(i?.error){n.message=`${i.error}: ${i.error_description}`}throw n}}});var Yu=F(ni=>{"use strict";Object.defineProperty(ni,"__esModule",{value:true});ni.ErrorWithCode=void 0;var To=class extends Error{code;constructor(e,n){super(e);this.code=n}};ni.ErrorWithCode=To});var wo=F(Io=>{"use strict";Object.defineProperty(Io,"__esModule",{value:true});Io.getCredentials=Gg;var Ug=z("path");var zu=z("fs");var Lg=z("util");var ii=Yu();var Xu=zu.readFile?(0,Lg.promisify)(zu.readFile):async()=>{throw new ii.ErrorWithCode("use key rather than keyFile.","MISSING_CREDENTIALS")};var ft;(function(t){t["JSON"]=".json";t["DER"]=".der";t["CRT"]=".crt";t["PEM"]=".pem";t["P12"]=".p12";t["PFX"]=".pfx"})(ft||(ft={}));var Ao=class{keyFilePath;constructor(e){this.keyFilePath=e}async getCredentials(){const e=await Xu(this.keyFilePath,"utf8");let n;try{n=JSON.parse(e)}catch(o){const l=o;throw new Error(`Invalid JSON key file: ${l.message}`)}const i=n.private_key;const r=n.client_email;if(!i||!r){throw new ii.ErrorWithCode("private_key and client_email are required.","MISSING_CREDENTIALS")}return{privateKey:i,clientEmail:r}}};var Co=class{keyFilePath;constructor(e){this.keyFilePath=e}async getCredentials(){const e=await Xu(this.keyFilePath,"utf8");return{privateKey:e}}};var vo=class{async getCredentials(){throw new ii.ErrorWithCode("*.p12 certificates are not supported after v6.1.2. Consider utilizing *.json format or converting *.p12 to *.pem using the OpenSSL CLI.","UNKNOWN_CERTIFICATE_TYPE")}};var So=class{static create(e){const n=Ug.extname(e);switch(n){case ft.JSON:return new Ao(e);case ft.DER:case ft.CRT:case ft.PEM:return new Co(e);case ft.P12:case ft.PFX:return new vo;default:throw new ii.ErrorWithCode("Unknown certificate type. Type is determined based on file extension. Current supported extensions are *.json, and *.pem.","UNKNOWN_CERTIFICATE_TYPE")}}};async function Gg(t){const e=So.create(t);return e.getCredentials()}});var Qu=F(ri=>{"use strict";Object.defineProperty(ri,"__esModule",{value:true});ri.TokenHandler=void 0;var Og=Wu();var bg=wo();var Ro=class{token;tokenExpiresAt;inFlightRequest;tokenOptions;constructor(e){this.tokenOptions=e}async processCredentials(){if(!this.tokenOptions.key&&!this.tokenOptions.keyFile){throw new Error("No key or keyFile set.")}if(!this.tokenOptions.key&&this.tokenOptions.keyFile){const e=await(0,bg.getCredentials)(this.tokenOptions.keyFile);this.tokenOptions.key=e.privateKey;this.tokenOptions.email=e.clientEmail}}isTokenExpiring(){if(!this.token||!this.tokenExpiresAt){return true}const e=new Date().getTime();const n=this.tokenOptions.eagerRefreshThresholdMillis??0;return this.tokenExpiresAt<=e+n}hasExpired(){const e=new Date().getTime();if(this.token&&this.tokenExpiresAt){const n=new Date().getTime();return n>=this.tokenExpiresAt}return true}async getToken(e){await this.processCredentials();if(this.inFlightRequest&&!e){return this.inFlightRequest}if(this.token&&!this.isTokenExpiring()&&!e){return this.token}try{this.inFlightRequest=(0,Og.getToken)(this.tokenOptions);const n=await this.inFlightRequest;this.token=n;this.tokenExpiresAt=new Date().getTime()+(n.expires_in??0)*1e3;return n}finally{this.inFlightRequest=void 0}}};ri.TokenHandler=Ro});var Zu=F(Po=>{"use strict";Object.defineProperty(Po,"__esModule",{value:true});Po.revokeToken=Hg;var Fg="https://oauth2.googleapis.com/revoke?token=";var qg=true;async function Hg(t,e){const n=Fg+t;return await e.request({url:n,retry:qg})}});var Mo=F(oi=>{"use strict";Object.defineProperty(oi,"__esModule",{value:true});oi.GoogleToken=void 0;var Vg=ge();var ju=Qu();var Bg=Zu();var No=class{tokenOptions;tokenHandler;constructor(e){this.tokenOptions=e||{};this.tokenOptions.transporter=this.tokenOptions.transporter||{request:n=>(0,Vg.request)(n)};if(!this.tokenOptions.iss){this.tokenOptions.iss=this.tokenOptions.email}if(typeof this.tokenOptions.scope==="object"){this.tokenOptions.scope=this.tokenOptions.scope.join(" ")}this.tokenHandler=new ju.TokenHandler(this.tokenOptions)}get expiresAt(){return this.tokenHandler.tokenExpiresAt}get accessToken(){return this.tokenHandler.token?.access_token}get idToken(){return this.tokenHandler.token?.id_token}get tokenType(){return this.tokenHandler.token?.token_type}get refreshToken(){return this.tokenHandler.token?.refresh_token}hasExpired(){return this.tokenHandler.hasExpired()}isTokenExpiring(){return this.tokenHandler.isTokenExpiring()}getToken(e,n={forceRefresh:false}){let i;if(typeof e==="function"){i=e}else if(typeof e==="object"){n=e}const r=this.tokenHandler.getToken(n.forceRefresh??false);if(i){r.then(o=>i(null,o),i)}return r}revokeToken(e){if(!this.accessToken){return Promise.reject(new Error("No token to revoke."))}const n=(0,Bg.revokeToken)(this.accessToken,this.tokenOptions.transporter);if(e){n.then(()=>e(),e)}this.tokenHandler=new ju.TokenHandler(this.tokenOptions)}get googleTokenOptions(){return this.tokenOptions}};oi.GoogleToken=No});var xo=F(si=>{"use strict";Object.defineProperty(si,"__esModule",{value:true});si.JWTAccess=void 0;var $g=Eo();var Jg=qe();var ec={alg:"RS256",typ:"JWT"};var ko=class t{email;key;keyId;projectId;eagerRefreshThresholdMillis;cache=new Jg.LRUCache({capacity:500,maxAge:60*60*1e3});constructor(e,n,i,r){this.email=e;this.key=n;this.keyId=i;this.eagerRefreshThresholdMillis=r??5*60*1e3}getCachedKey(e,n){let i=e;if(n&&Array.isArray(n)&&n.length){i=e?`${e}_${n.join("_")}`:`${n.join("_")}`}else if(typeof n==="string"){i=e?`${e}_${n}`:n}if(!i){throw Error("Scopes or url must be provided")}return i}getRequestHeaders(e,n,i){const r=this.getCachedKey(e,i);const o=this.cache.get(r);const l=Date.now();if(o&&o.expiration-l>this.eagerRefreshThresholdMillis){return new Headers(o.headers)}const u=Math.floor(Date.now()/1e3);const c=t.getExpirationTime(u);let d;if(Array.isArray(i)){i=i.join(" ")}if(i){d={iss:this.email,sub:this.email,scope:i,exp:c,iat:u}}else{d={iss:this.email,sub:this.email,aud:e,exp:c,iat:u}}if(n){for(const _ in d){if(n[_]){throw new Error(`The '${_}' property is not allowed when passing additionalClaims. This claim is included in the JWT by default.`)}}}const f=this.keyId?{...ec,kid:this.keyId}:ec;const p=Object.assign(d,n);const h=$g.sign({header:f,payload:p,secret:this.key});const m=new Headers({authorization:`Bearer ${h}`});this.cache.set(r,{expiration:c*1e3,headers:m});return m}static getExpirationTime(e){const n=e+3600;return n}fromJSON(e){if(!e){throw new Error("Must pass in a JSON object containing the service account auth settings.")}if(!e.client_email){throw new Error("The incoming JSON object does not contain a client_email field")}if(!e.private_key){throw new Error("The incoming JSON object does not contain a private_key field")}this.email=e.client_email;this.key=e.private_key;this.keyId=e.private_key_id;this.projectId=e.project_id}fromStream(e,n){if(n){this.fromStreamAsync(e).then(()=>n(),n)}else{return this.fromStreamAsync(e)}}fromStreamAsync(e){return new Promise((n,i)=>{if(!e){i(new Error("Must pass in a stream containing the service account auth settings."))}let r="";e.setEncoding("utf8").on("data",o=>r+=o).on("error",i).on("end",()=>{try{const o=JSON.parse(r);this.fromJSON(o);n()}catch(o){i(o)}})})}};si.JWTAccess=ko});var Uo=F(li=>{"use strict";Object.defineProperty(li,"__esModule",{value:true});li.JWT=void 0;var tc=Mo();var Kg=wo();var Wg=xo();var Yg=ct();var ai=Pe();var Do=class t extends Yg.OAuth2Client{email;keyFile;key;keyId;defaultScopes;scopes;scope;subject;gtoken;additionalClaims;useJWTAccessWithScope;defaultServicePath;access;constructor(e={}){super(e);this.email=e.email;this.keyFile=e.keyFile;this.key=e.key;this.keyId=e.keyId;this.scopes=e.scopes;this.subject=e.subject;this.additionalClaims=e.additionalClaims;this.credentials={refresh_token:"jwt-placeholder",expiry_date:1}}createScoped(e){const n=new t(this);n.scopes=e;return n}async getRequestMetadataAsync(e){e=this.defaultServicePath?`https://${this.defaultServicePath}/`:e;const n=!this.hasUserScopes()&&e||this.useJWTAccessWithScope&&this.hasAnyScopes()||this.universeDomain!==ai.DEFAULT_UNIVERSE;if(this.subject&&this.universeDomain!==ai.DEFAULT_UNIVERSE){throw new RangeError(`Service Account user is configured for the credential. Domain-wide delegation is not supported in universes other than ${ai.DEFAULT_UNIVERSE}`)}if(!this.apiKey&&n){if(this.additionalClaims&&this.additionalClaims.target_audience){const{tokens:i}=await this.refreshToken();return{headers:this.addSharedMetadataHeaders(new Headers({authorization:`Bearer ${i.id_token}`}))}}else{if(!this.access){this.access=new Wg.JWTAccess(this.email,this.key,this.keyId,this.eagerRefreshThresholdMillis)}let i;if(this.hasUserScopes()){i=this.scopes}else if(!e){i=this.defaultScopes}const r=this.useJWTAccessWithScope||this.universeDomain!==ai.DEFAULT_UNIVERSE;const o=await this.access.getRequestHeaders(e??void 0,this.additionalClaims,r?i:void 0);return{headers:this.addSharedMetadataHeaders(o)}}}else if(this.hasAnyScopes()||this.apiKey){return super.getRequestMetadataAsync(e)}else{return{headers:new Headers}}}async fetchIdToken(e){const n=new tc.GoogleToken({iss:this.email,sub:this.subject,scope:this.scopes||this.defaultScopes,keyFile:this.keyFile,key:this.key,additionalClaims:{target_audience:e},transporter:this.transporter});await n.getToken({forceRefresh:true});if(!n.idToken){throw new Error("Unknown error: Failed to fetch ID token")}return n.idToken}hasUserScopes(){if(!this.scopes){return false}return this.scopes.length>0}hasAnyScopes(){if(this.scopes&&this.scopes.length>0)return true;if(this.defaultScopes&&this.defaultScopes.length>0)return true;return false}authorize(e){if(e){this.authorizeAsync().then(n=>e(null,n),e)}else{return this.authorizeAsync()}}async authorizeAsync(){const e=await this.refreshToken();if(!e){throw new Error("No result returned")}this.credentials=e.tokens;this.credentials.refresh_token="jwt-placeholder";this.key=this.gtoken.googleTokenOptions?.key;this.email=this.gtoken.googleTokenOptions?.iss;return e.tokens}async refreshTokenNoCache(){const e=this.createGToken();const n=await e.getToken({forceRefresh:this.isTokenExpiring()});const i={access_token:n.access_token,token_type:"Bearer",expiry_date:e.expiresAt,id_token:e.idToken};this.emit("tokens",i);return{res:null,tokens:i}}createGToken(){if(!this.gtoken){this.gtoken=new tc.GoogleToken({iss:this.email,sub:this.subject,scope:this.scopes||this.defaultScopes,keyFile:this.keyFile,key:this.key,additionalClaims:this.additionalClaims,transporter:this.transporter})}return this.gtoken}fromJSON(e){if(!e){throw new Error("Must pass in a JSON object containing the service account auth settings.")}if(!e.client_email){throw new Error("The incoming JSON object does not contain a client_email field")}if(!e.private_key){throw new Error("The incoming JSON object does not contain a private_key field")}this.email=e.client_email;this.key=e.private_key;this.keyId=e.private_key_id;this.projectId=e.project_id;this.quotaProjectId=e.quota_project_id;this.universeDomain=e.universe_domain||this.universeDomain}fromStream(e,n){if(n){this.fromStreamAsync(e).then(()=>n(),n)}else{return this.fromStreamAsync(e)}}fromStreamAsync(e){return new Promise((n,i)=>{if(!e){throw new Error("Must pass in a stream containing the service account auth settings.")}let r="";e.setEncoding("utf8").on("error",i).on("data",o=>r+=o).on("end",()=>{try{const o=JSON.parse(r);this.fromJSON(o);n()}catch(o){i(o)}})})}fromAPIKey(e){if(typeof e!=="string"){throw new Error("Must provide an API Key string.")}this.apiKey=e}async getCredentials(){if(this.key){return{private_key:this.key,client_email:this.email}}else if(this.keyFile){const e=this.createGToken();const n=await(0,Kg.getCredentials)(this.keyFile);return{private_key:n.privateKey,client_email:n.clientEmail}}throw new Error("A key or a keyFile must be provided to getCredentials.")}};li.JWT=Do});var Go=F(Vt=>{"use strict";Object.defineProperty(Vt,"__esModule",{value:true});Vt.UserRefreshClient=Vt.USER_REFRESH_ACCOUNT_TYPE=void 0;var zg=ct();var Xg=Pe();Vt.USER_REFRESH_ACCOUNT_TYPE="authorized_user";var Lo=class t extends zg.OAuth2Client{_refreshToken;constructor(e,n,i,r,o){const l=e&&typeof e==="object"?e:{clientId:e,clientSecret:n,refreshToken:i,eagerRefreshThresholdMillis:r,forceRefreshOnFailure:o};super(l);this._refreshToken=l.refreshToken;this.credentials.refresh_token=l.refreshToken}async refreshTokenNoCache(){return super.refreshTokenNoCache(this._refreshToken)}async fetchIdToken(e){const n={...t.RETRY_CONFIG,url:this.endpoints.oauth2TokenUrl,method:"POST",data:new URLSearchParams({client_id:this._clientId,client_secret:this._clientSecret,grant_type:"refresh_token",refresh_token:this._refreshToken,target_audience:e}),responseType:"json"};Xg.AuthClient.setMethodName(n,"fetchIdToken");const i=await this.transporter.request(n);return i.data.id_token}fromJSON(e){if(!e){throw new Error("Must pass in a JSON object containing the user refresh token")}if(e.type!=="authorized_user"){throw new Error('The incoming JSON object does not have the "authorized_user" type')}if(!e.client_id){throw new Error("The incoming JSON object does not contain a client_id field")}if(!e.client_secret){throw new Error("The incoming JSON object does not contain a client_secret field")}if(!e.refresh_token){throw new Error("The incoming JSON object does not contain a refresh_token field")}this._clientId=e.client_id;this._clientSecret=e.client_secret;this._refreshToken=e.refresh_token;this.credentials.refresh_token=e.refresh_token;this.quotaProjectId=e.quota_project_id;this.universeDomain=e.universe_domain||this.universeDomain}fromStream(e,n){if(n){this.fromStreamAsync(e).then(()=>n(),n)}else{return this.fromStreamAsync(e)}}async fromStreamAsync(e){return new Promise((n,i)=>{if(!e){return i(new Error("Must pass in a stream containing the user refresh token."))}let r="";e.setEncoding("utf8").on("error",i).on("data",o=>r+=o).on("end",()=>{try{const o=JSON.parse(r);this.fromJSON(o);return n()}catch(o){return i(o)}})})}static fromJSON(e){const n=new t;n.fromJSON(e);return n}};Vt.UserRefreshClient=Lo});var bo=F(Bt=>{"use strict";Object.defineProperty(Bt,"__esModule",{value:true});Bt.Impersonated=Bt.IMPERSONATED_ACCOUNT_TYPE=void 0;var nc=ct();var Qg=ge();var Zg=qe();Bt.IMPERSONATED_ACCOUNT_TYPE="impersonated_service_account";var Oo=class t extends nc.OAuth2Client{sourceClient;targetPrincipal;targetScopes;delegates;lifetime;endpoint;constructor(e={}){super(e);this.credentials={expiry_date:1,refresh_token:"impersonated-placeholder"};this.sourceClient=e.sourceClient??new nc.OAuth2Client;this.targetPrincipal=e.targetPrincipal??"";this.delegates=e.delegates??[];this.targetScopes=e.targetScopes??[];this.lifetime=e.lifetime??3600;const n=!!(0,Zg.originalOrCamelOptions)(e).get("universe_domain");if(!n){this.universeDomain=this.sourceClient.universeDomain}else if(this.sourceClient.universeDomain!==this.universeDomain){throw new RangeError(`Universe domain ${this.sourceClient.universeDomain} in source credentials does not match ${this.universeDomain} universe domain set for impersonated credentials.`)}this.endpoint=e.endpoint??`https://iamcredentials.${this.universeDomain}`}async sign(e){await this.sourceClient.getAccessToken();const n=`projects/-/serviceAccounts/${this.targetPrincipal}`;const i=`${this.endpoint}/v1/${n}:signBlob`;const r={delegates:this.delegates,payload:Buffer.from(e).toString("base64")};const o=await this.sourceClient.request({...t.RETRY_CONFIG,url:i,data:r,method:"POST"});return o.data}getTargetPrincipal(){return this.targetPrincipal}async refreshToken(){try{await this.sourceClient.getAccessToken();const e="projects/-/serviceAccounts/"+this.targetPrincipal;const n=`${this.endpoint}/v1/${e}:generateAccessToken`;const i={delegates:this.delegates,scope:this.targetScopes,lifetime:this.lifetime+"s"};const r=await this.sourceClient.request({...t.RETRY_CONFIG,url:n,data:i,method:"POST"});const o=r.data;this.credentials.access_token=o.accessToken;this.credentials.expiry_date=Date.parse(o.expireTime);return{tokens:this.credentials,res:r}}catch(e){if(!(e instanceof Error))throw e;let n=0;let i="";if(e instanceof Qg.GaxiosError){n=e?.response?.data?.error?.status;i=e?.response?.data?.error?.message}if(n&&i){e.message=`${n}: unable to impersonate: ${i}`;throw e}else{e.message=`unable to impersonate: ${e}`;throw e}}}async fetchIdToken(e,n){await this.sourceClient.getAccessToken();const i=`projects/-/serviceAccounts/${this.targetPrincipal}`;const r=`${this.endpoint}/v1/${i}:generateIdToken`;const o={delegates:this.delegates,audience:e,includeEmail:n?.includeEmail??true,useEmailAzp:n?.includeEmail??true};const l=await this.sourceClient.request({...t.RETRY_CONFIG,url:r,data:o,method:"POST"});return l.data.token}};Bt.Impersonated=Oo});var qo=F(En=>{"use strict";Object.defineProperty(En,"__esModule",{value:true});En.OAuthClientAuthHandler=void 0;En.getErrorFromOAuthErrorResponse=tm;var $t=ge();var jg=fn();var em=["PUT","POST","PATCH"];var Fo=class{#e=(0,jg.createCrypto)();#t;transporter;constructor(e){if(e&&"clientId"in e){this.#t=e;this.transporter=new $t.Gaxios}else{this.#t=e?.clientAuthentication;this.transporter=e?.transporter||new $t.Gaxios}}applyClientAuthenticationOptions(e,n){e.headers=$t.Gaxios.mergeHeaders(e.headers);this.injectAuthenticatedHeaders(e,n);if(!n){this.injectAuthenticatedRequestBody(e)}}injectAuthenticatedHeaders(e,n){if(n){e.headers=$t.Gaxios.mergeHeaders(e.headers,{authorization:`Bearer ${n}`})}else if(this.#t?.confidentialClientType==="basic"){e.headers=$t.Gaxios.mergeHeaders(e.headers);const i=this.#t.clientId;const r=this.#t.clientSecret||"";const o=this.#e.encodeBase64StringUtf8(`${i}:${r}`);$t.Gaxios.mergeHeaders(e.headers,{authorization:`Basic ${o}`})}}injectAuthenticatedRequestBody(e){if(this.#t?.confidentialClientType==="request-body"){const n=(e.method||"GET").toUpperCase();if(!em.includes(n)){throw new Error(`${n} HTTP method does not support ${this.#t.confidentialClientType} client authentication`)}const i=new Headers(e.headers);const r=i.get("content-type");if(r?.startsWith("application/x-www-form-urlencoded")||e.data instanceof URLSearchParams){const o=new URLSearchParams(e.data??"");o.append("client_id",this.#t.clientId);o.append("client_secret",this.#t.clientSecret||"");e.data=o}else if(r?.startsWith("application/json")){e.data=e.data||{};Object.assign(e.data,{client_id:this.#t.clientId,client_secret:this.#t.clientSecret||""})}else{throw new Error(`${r} content-types are not supported with ${this.#t.confidentialClientType} client authentication`)}}}static get RETRY_CONFIG(){return{retry:true,retryConfig:{httpMethodsToRetry:["GET","PUT","POST","HEAD","OPTIONS","DELETE"]}}}};En.OAuthClientAuthHandler=Fo;function tm(t,e){const n=t.error;const i=t.error_description;const r=t.error_uri;let o=`Error code ${n}`;if(typeof i!=="undefined"){o+=`: ${i}`}if(typeof r!=="undefined"){o+=` - ${r}`}const l=new Error(o);if(e){const u=Object.keys(e);if(e.stack){u.push("stack")}u.forEach(c=>{if(c!=="message"){Object.defineProperty(l,c,{value:e[c],writable:false,enumerable:true})}})}return l}});var ci=F(ui=>{"use strict";Object.defineProperty(ui,"__esModule",{value:true});ui.StsCredentials=void 0;var nm=ge();var im=Pe();var ic=qo();var rm=qe();var Ho=class t extends ic.OAuthClientAuthHandler{#e;constructor(e={tokenExchangeEndpoint:""},n){if(typeof e!=="object"||e instanceof URL){e={tokenExchangeEndpoint:e,clientAuthentication:n}}super(e);this.#e=e.tokenExchangeEndpoint}async exchangeToken(e,n,i){const r={grant_type:e.grantType,resource:e.resource,audience:e.audience,scope:e.scope?.join(" "),requested_token_type:e.requestedTokenType,subject_token:e.subjectToken,subject_token_type:e.subjectTokenType,actor_token:e.actingParty?.actorToken,actor_token_type:e.actingParty?.actorTokenType,options:i&&JSON.stringify(i)};const o={...t.RETRY_CONFIG,url:this.#e.toString(),method:"POST",headers:n,data:new URLSearchParams((0,rm.removeUndefinedValuesInObject)(r)),responseType:"json"};im.AuthClient.setMethodName(o,"exchangeToken");this.applyClientAuthenticationOptions(o);try{const l=await this.transporter.request(o);const u=l.data;u.res=l;return u}catch(l){if(l instanceof nm.GaxiosError&&l.response){throw(0,ic.getErrorFromOAuthErrorResponse)(l.response.data,l)}throw l}}};ui.StsCredentials=Ho});var pt=F(Ge=>{"use strict";Object.defineProperty(Ge,"__esModule",{value:true});Ge.BaseExternalAccountClient=Ge.CLOUD_RESOURCE_MANAGER=Ge.EXTERNAL_ACCOUNT_TYPE=Ge.EXPIRATION_TIME_OFFSET=void 0;var om=ge();var sm=z("stream");var Vo=Pe();var am=ci();var rc=qe();var lm=Xr();var um="urn:ietf:params:oauth:grant-type:token-exchange";var cm="urn:ietf:params:oauth:token-type:access_token";var Bo="https://www.googleapis.com/auth/cloud-platform";var dm=3600;Ge.EXPIRATION_TIME_OFFSET=5*60*1e3;Ge.EXTERNAL_ACCOUNT_TYPE="external_account";Ge.CLOUD_RESOURCE_MANAGER="https://cloudresourcemanager.googleapis.com/v1/projects/";var fm="//iam\\.googleapis\\.com/locations/[^/]+/workforcePools/[^/]+/providers/.+";var pm="https://sts.{universeDomain}/v1/token";var $o=class t extends Vo.AuthClient{scopes;projectNumber;audience;subjectTokenType;stsCredential;clientAuth;credentialSourceType;cachedAccessToken;serviceAccountImpersonationUrl;serviceAccountImpersonationLifetime;workforcePoolUserProject;configLifetimeRequested;tokenUrl;cloudResourceManagerURL;supplierContext;#e=null;constructor(e){super(e);const n=(0,rc.originalOrCamelOptions)(e);const i=n.get("type");if(i&&i!==Ge.EXTERNAL_ACCOUNT_TYPE){throw new Error(`Expected "${Ge.EXTERNAL_ACCOUNT_TYPE}" type but received "${e.type}"`)}const r=n.get("client_id");const o=n.get("client_secret");this.tokenUrl=n.get("token_url")??pm.replace("{universeDomain}",this.universeDomain);const l=n.get("subject_token_type");const u=n.get("workforce_pool_user_project");const c=n.get("service_account_impersonation_url");const d=n.get("service_account_impersonation");const f=(0,rc.originalOrCamelOptions)(d).get("token_lifetime_seconds");this.cloudResourceManagerURL=new URL(n.get("cloud_resource_manager_url")||`https://cloudresourcemanager.${this.universeDomain}/v1/projects/`);if(r){this.clientAuth={confidentialClientType:"basic",clientId:r,clientSecret:o}}this.stsCredential=new am.StsCredentials({tokenExchangeEndpoint:this.tokenUrl,clientAuthentication:this.clientAuth});this.scopes=n.get("scopes")||[Bo];this.cachedAccessToken=null;this.audience=n.get("audience");this.subjectTokenType=l;this.workforcePoolUserProject=u;const p=new RegExp(fm);if(this.workforcePoolUserProject&&!this.audience.match(p)){throw new Error("workforcePoolUserProject should not be set for non-workforce pool credentials.")}this.serviceAccountImpersonationUrl=c;this.serviceAccountImpersonationLifetime=f;if(this.serviceAccountImpersonationLifetime){this.configLifetimeRequested=true}else{this.configLifetimeRequested=false;this.serviceAccountImpersonationLifetime=dm}this.projectNumber=this.getProjectNumber(this.audience);this.supplierContext={audience:this.audience,subjectTokenType:this.subjectTokenType,transporter:this.transporter}}getServiceAccountEmail(){if(this.serviceAccountImpersonationUrl){if(this.serviceAccountImpersonationUrl.length>256){throw new RangeError(`URL is too long: ${this.serviceAccountImpersonationUrl}`)}const e=/serviceAccounts\/(?<email>[^:]+):generateAccessToken$/;const n=e.exec(this.serviceAccountImpersonationUrl);return n?.groups?.email||null}return null}setCredentials(e){super.setCredentials(e);this.cachedAccessToken=e}async getAccessToken(){if(!this.cachedAccessToken||this.isExpired(this.cachedAccessToken)){await this.refreshAccessTokenAsync()}return{token:this.cachedAccessToken.access_token,res:this.cachedAccessToken.res}}async getRequestHeaders(){const e=await this.getAccessToken();const n=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(n)}request(e,n){if(n){this.requestAsync(e).then(i=>n(null,i),i=>{return n(i,i.response)})}else{return this.requestAsync(e)}}async getProjectId(){const e=this.projectNumber||this.workforcePoolUserProject;if(this.projectId){return this.projectId}else if(e){const n=await this.getRequestHeaders();const i={...t.RETRY_CONFIG,headers:n,url:`${this.cloudResourceManagerURL.toString()}${e}`,responseType:"json"};Vo.AuthClient.setMethodName(i,"getProjectId");const r=await this.transporter.request(i);this.projectId=r.data.projectId;return this.projectId}return null}async requestAsync(e,n=false){let i;try{const r=await this.getRequestHeaders();e.headers=om.Gaxios.mergeHeaders(e.headers);this.addUserProjectAndAuthHeaders(e.headers,r);i=await this.transporter.request(e)}catch(r){const o=r.response;if(o){const l=o.status;const u=o.config.data instanceof sm.Readable;const c=l===401||l===403;if(!n&&c&&!u&&this.forceRefreshOnFailure){await this.refreshAccessTokenAsync();return await this.requestAsync(e,true)}}throw r}return i}async refreshAccessTokenAsync(){this.#e=this.#e||this.#t();try{return await this.#e}finally{this.#e=null}}async#t(){const e=await this.retrieveSubjectToken();const n={grantType:um,audience:this.audience,requestedTokenType:cm,subjectToken:e,subjectTokenType:this.subjectTokenType,scope:this.serviceAccountImpersonationUrl?[Bo]:this.getScopesArray()};const i=!this.clientAuth&&this.workforcePoolUserProject?{userProject:this.workforcePoolUserProject}:void 0;const r=new Headers({"x-goog-api-client":this.getMetricsHeaderValue()});const o=await this.stsCredential.exchangeToken(n,r,i);if(this.serviceAccountImpersonationUrl){this.cachedAccessToken=await this.getImpersonatedAccessToken(o.access_token)}else if(o.expires_in){this.cachedAccessToken={access_token:o.access_token,expiry_date:new Date().getTime()+o.expires_in*1e3,res:o.res}}else{this.cachedAccessToken={access_token:o.access_token,res:o.res}}this.credentials={};Object.assign(this.credentials,this.cachedAccessToken);delete this.credentials.res;this.emit("tokens",{refresh_token:null,expiry_date:this.cachedAccessToken.expiry_date,access_token:this.cachedAccessToken.access_token,token_type:"Bearer",id_token:null});return this.cachedAccessToken}getProjectNumber(e){const n=e.match(/\/projects\/([^/]+)/);if(!n){return null}return n[1]}async getImpersonatedAccessToken(e){const n={...t.RETRY_CONFIG,url:this.serviceAccountImpersonationUrl,method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},data:{scope:this.getScopesArray(),lifetime:this.serviceAccountImpersonationLifetime+"s"},responseType:"json"};Vo.AuthClient.setMethodName(n,"getImpersonatedAccessToken");const i=await this.transporter.request(n);const r=i.data;return{access_token:r.accessToken,expiry_date:new Date(r.expireTime).getTime(),res:i}}isExpired(e){const n=new Date().getTime();return e.expiry_date?n>=e.expiry_date-this.eagerRefreshThresholdMillis:false}getScopesArray(){if(typeof this.scopes==="string"){return[this.scopes]}return this.scopes||[Bo]}getMetricsHeaderValue(){const e=process.version.replace(/^v/,"");const n=this.serviceAccountImpersonationUrl!==void 0;const i=this.credentialSourceType?this.credentialSourceType:"unknown";return`gl-node/${e} auth/${lm.pkg.version} google-byoid-sdk source/${i} sa-impersonation/${n} config-lifetime/${this.configLifetimeRequested}`}getTokenUrl(){return this.tokenUrl}};Ge.BaseExternalAccountClient=$o});var oc=F(di=>{"use strict";Object.defineProperty(di,"__esModule",{value:true});di.FileSubjectTokenSupplier=void 0;var Ko=z("util");var Wo=z("fs");var hm=(0,Ko.promisify)(Wo.readFile??(()=>{}));var gm=(0,Ko.promisify)(Wo.realpath??(()=>{}));var mm=(0,Ko.promisify)(Wo.lstat??(()=>{}));var Jo=class{filePath;formatType;subjectTokenFieldName;constructor(e){this.filePath=e.filePath;this.formatType=e.formatType;this.subjectTokenFieldName=e.subjectTokenFieldName}async getSubjectToken(){let e=this.filePath;try{e=await gm(e);if(!(await mm(e)).isFile()){throw new Error}}catch(r){if(r instanceof Error){r.message=`The file at ${e} does not exist, or it is not a file. ${r.message}`}throw r}let n;const i=await hm(e,{encoding:"utf8"});if(this.formatType==="text"){n=i}else if(this.formatType==="json"&&this.subjectTokenFieldName){const r=JSON.parse(i);n=r[this.subjectTokenFieldName]}if(!n){throw new Error("Unable to parse the subject_token from the credential_source file")}return n}};di.FileSubjectTokenSupplier=Jo});var sc=F(fi=>{"use strict";Object.defineProperty(fi,"__esModule",{value:true});fi.UrlSubjectTokenSupplier=void 0;var ym=Pe();var Yo=class{url;headers;formatType;subjectTokenFieldName;additionalGaxiosOptions;constructor(e){this.url=e.url;this.formatType=e.formatType;this.subjectTokenFieldName=e.subjectTokenFieldName;this.headers=e.headers;this.additionalGaxiosOptions=e.additionalGaxiosOptions}async getSubjectToken(e){const n={...this.additionalGaxiosOptions,url:this.url,method:"GET",headers:this.headers,responseType:this.formatType};ym.AuthClient.setMethodName(n,"getSubjectToken");let i;if(this.formatType==="text"){const r=await e.transporter.request(n);i=r.data}else if(this.formatType==="json"&&this.subjectTokenFieldName){const r=await e.transporter.request(n);i=r.data[this.subjectTokenFieldName]}if(!i){throw new Error("Unable to parse the subject_token from the credential_source URL")}return i}};fi.UrlSubjectTokenSupplier=Yo});var ac=F(Ne=>{"use strict";Object.defineProperty(Ne,"__esModule",{value:true});Ne.CertificateSubjectTokenSupplier=Ne.InvalidConfigurationError=Ne.CertificateSourceUnavailableError=Ne.CERTIFICATE_CONFIGURATION_ENV_VARIABLE=void 0;var pi=qe();var hi=z("fs");var gi=z("crypto");var Em=z("https");Ne.CERTIFICATE_CONFIGURATION_ENV_VARIABLE="GOOGLE_API_CERTIFICATE_CONFIG";var je=class extends Error{constructor(e){super(e);this.name="CertificateSourceUnavailableError"}};Ne.CertificateSourceUnavailableError=je;var Oe=class extends Error{constructor(e){super(e);this.name="InvalidConfigurationError"}};Ne.InvalidConfigurationError=Oe;var zo=class{certificateConfigPath;trustChainPath;cert;key;constructor(e){if(!e.useDefaultCertificateConfig&&!e.certificateConfigLocation){throw new Oe("Either `useDefaultCertificateConfig` must be true or a `certificateConfigLocation` must be provided.")}if(e.useDefaultCertificateConfig&&e.certificateConfigLocation){throw new Oe("Both `useDefaultCertificateConfig` and `certificateConfigLocation` cannot be provided.")}this.trustChainPath=e.trustChainPath;this.certificateConfigPath=e.certificateConfigLocation??""}async createMtlsHttpsAgent(){if(!this.key||!this.cert){throw new Oe("Cannot create mTLS Agent with missing certificate or key")}return new Em.Agent({key:this.key,cert:this.cert})}async getSubjectToken(){this.certificateConfigPath=await this.#e();const{certPath:e,keyPath:n}=await this.#t();({cert:this.cert,key:this.key}=await this.#n(e,n));return await this.#i(this.cert)}async#e(){const e=this.certificateConfigPath;if(e){if(await(0,pi.isValidFile)(e)){return e}throw new je(`Provided certificate config path is invalid: ${e}`)}const n=process.env[Ne.CERTIFICATE_CONFIGURATION_ENV_VARIABLE];if(n){if(await(0,pi.isValidFile)(n)){return n}throw new je(`Path from environment variable "${Ne.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" is invalid: ${n}`)}const i=(0,pi.getWellKnownCertificateConfigFileLocation)();if(await(0,pi.isValidFile)(i)){return i}throw new je(`Could not find certificate configuration file. Searched override path, the "${Ne.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" env var, and the gcloud path (${i}).`)}async#t(){const e=this.certificateConfigPath;let n;try{n=await hi.promises.readFile(e,"utf8")}catch(i){throw new je(`Failed to read certificate config file at: ${e}`)}try{const i=JSON.parse(n);const r=i?.cert_configs?.workload?.cert_path;const o=i?.cert_configs?.workload?.key_path;if(!r||!o){throw new Oe(`Certificate config file (${e}) is missing required "cert_path" or "key_path" in the workload config.`)}return{certPath:r,keyPath:o}}catch(i){if(i instanceof Oe)throw i;throw new Oe(`Failed to parse certificate config from ${e}: ${i.message}`)}}async#n(e,n){let i,r;try{i=await hi.promises.readFile(e);new gi.X509Certificate(i)}catch(o){const l=o instanceof Error?o.message:String(o);throw new je(`Failed to read certificate file at ${e}: ${l}`)}try{r=await hi.promises.readFile(n);(0,gi.createPrivateKey)(r)}catch(o){const l=o instanceof Error?o.message:String(o);throw new je(`Failed to read private key file at ${n}: ${l}`)}return{cert:i,key:r}}async#i(e){const n=new gi.X509Certificate(e);if(!this.trustChainPath){return JSON.stringify([n.raw.toString("base64")])}try{const i=await hi.promises.readFile(this.trustChainPath,"utf8");const r=i.match(/-----BEGIN CERTIFICATE-----[^-]+-----END CERTIFICATE-----/g)??[];const o=r.map((c,d)=>{try{return new gi.X509Certificate(c)}catch(f){const p=f instanceof Error?f.message:String(f);throw new Oe(`Failed to parse certificate at index ${d} in trust chain file ${this.trustChainPath}: ${p}`)}});const l=o.findIndex(c=>n.raw.equals(c.raw));let u;if(l===-1){u=[n,...o]}else if(l===0){u=o}else{throw new Oe(`Leaf certificate exists in the trust chain but is not the first entry (found at index ${l}).`)}return JSON.stringify(u.map(c=>c.raw.toString("base64")))}catch(i){if(i instanceof Oe)throw i;const r=i instanceof Error?i.message:String(i);throw new je(`Failed to process certificate chain from ${this.trustChainPath}: ${r}`)}}};Ne.CertificateSubjectTokenSupplier=zo});var Zo=F(mi=>{"use strict";Object.defineProperty(mi,"__esModule",{value:true});mi.IdentityPoolClient=void 0;var _m=pt();var Xo=qe();var Tm=oc();var Am=sc();var lc=ac();var Cm=ci();var uc=ge();var Qo=class t extends _m.BaseExternalAccountClient{subjectTokenSupplier;constructor(e){super(e);const n=(0,Xo.originalOrCamelOptions)(e);const i=n.get("credential_source");const r=n.get("subject_token_supplier");if(!i&&!r){throw new Error("A credential source or subject token supplier must be specified.")}if(i&&r){throw new Error("Only one of credential source or subject token supplier can be specified.")}if(r){this.subjectTokenSupplier=r;this.credentialSourceType="programmatic"}else{const o=(0,Xo.originalOrCamelOptions)(i);const l=(0,Xo.originalOrCamelOptions)(o.get("format"));const u=l.get("type")||"text";const c=l.get("subject_token_field_name");if(u!=="json"&&u!=="text"){throw new Error(`Invalid credential_source format "${u}"`)}if(u==="json"&&!c){throw new Error("Missing subject_token_field_name for JSON credential_source format")}const d=o.get("file");const f=o.get("url");const p=o.get("certificate");const h=o.get("headers");if(d&&f||f&&p||d&&p){throw new Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.')}else if(d){this.credentialSourceType="file";this.subjectTokenSupplier=new Tm.FileSubjectTokenSupplier({filePath:d,formatType:u,subjectTokenFieldName:c})}else if(f){this.credentialSourceType="url";this.subjectTokenSupplier=new Am.UrlSubjectTokenSupplier({url:f,formatType:u,subjectTokenFieldName:c,headers:h,additionalGaxiosOptions:t.RETRY_CONFIG})}else if(p){this.credentialSourceType="certificate";const m=new lc.CertificateSubjectTokenSupplier({useDefaultCertificateConfig:p.use_default_certificate_config,certificateConfigLocation:p.certificate_config_location,trustChainPath:p.trust_chain_path});this.subjectTokenSupplier=m}else{throw new Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.')}}}async retrieveSubjectToken(){const e=await this.subjectTokenSupplier.getSubjectToken(this.supplierContext);if(this.subjectTokenSupplier instanceof lc.CertificateSubjectTokenSupplier){const n=await this.subjectTokenSupplier.createMtlsHttpsAgent();this.stsCredential=new Cm.StsCredentials({tokenExchangeEndpoint:this.getTokenUrl(),clientAuthentication:this.clientAuth,transporter:new uc.Gaxios({agent:n})});this.transporter=new uc.Gaxios({...this.transporter.defaults||{},agent:n})}return e}};mi.IdentityPoolClient=Qo});var es=F(Ei=>{"use strict";Object.defineProperty(Ei,"__esModule",{value:true});Ei.AwsRequestSigner=void 0;var yi=ge();var dc=fn();var cc="AWS4-HMAC-SHA256";var vm="aws4_request";var jo=class{getCredentials;region;crypto;constructor(e,n){this.getCredentials=e;this.region=n;this.crypto=(0,dc.createCrypto)()}async getRequestOptions(e){if(!e.url){throw new RangeError('"url" is required in "amzOptions"')}const n=typeof e.data==="object"?JSON.stringify(e.data):e.data;const i=e.url;const r=e.method||"GET";const o=e.body||n;const l=e.headers;const u=await this.getCredentials();const c=new URL(i);if(typeof o!=="string"&&o!==void 0){throw new TypeError(`'requestPayload' is expected to be a string if provided. Got: ${o}`)}const d=await Im({crypto:this.crypto,host:c.host,canonicalUri:c.pathname,canonicalQuerystring:c.search.slice(1),method:r,region:this.region,securityCredentials:u,requestPayload:o,additionalAmzHeaders:l});const f=yi.Gaxios.mergeHeaders(d.amzDate?{"x-amz-date":d.amzDate}:{},{authorization:d.authorizationHeader,host:c.host},l||{});if(u.token){yi.Gaxios.mergeHeaders(f,{"x-amz-security-token":u.token})}const p={url:i,method:r,headers:f};if(o!==void 0){p.body=o}return p}};Ei.AwsRequestSigner=jo;async function _n(t,e,n){return await t.signWithHmacSha256(e,n)}async function Sm(t,e,n,i,r){const o=await _n(t,`AWS4${e}`,n);const l=await _n(t,o,i);const u=await _n(t,l,r);const c=await _n(t,u,"aws4_request");return c}async function Im(t){const e=yi.Gaxios.mergeHeaders(t.additionalAmzHeaders);const n=t.requestPayload||"";const i=t.host.split(".")[0];const r=new Date;const o=r.toISOString().replace(/[-:]/g,"").replace(/\.[0-9]+/,"");const l=r.toISOString().replace(/[-]/g,"").replace(/T.*/,"");if(t.securityCredentials.token){e.set("x-amz-security-token",t.securityCredentials.token)}const u=yi.Gaxios.mergeHeaders({host:t.host},e.has("date")?{}:{"x-amz-date":o},e);let c="";const d=[...u.keys()].sort();d.forEach(G=>{c+=`${G}:${u.get(G)}
6
+ `});const f=d.join(";");const p=await t.crypto.sha256DigestHex(n);const h=`${t.method.toUpperCase()}
7
+ ${t.canonicalUri}
8
+ ${t.canonicalQuerystring}
9
+ ${c}
10
+ ${f}
11
+ ${p}`;const m=`${l}/${t.region}/${i}/${vm}`;const _=`${cc}
12
+ ${o}
13
+ ${m}
14
+ `+await t.crypto.sha256DigestHex(h);const A=await Sm(t.crypto,t.securityCredentials.secretAccessKey,l,t.region,i);const T=await _n(t.crypto,A,_);const v=`${cc} Credential=${t.securityCredentials.accessKeyId}/${m}, SignedHeaders=${f}, Signature=${(0,dc.fromArrayBufferToHex)(T)}`;return{amzDate:e.has("date")?void 0:o,authorizationHeader:v,canonicalQuerystring:t.canonicalQuerystring}}});var fc=F(Ti=>{"use strict";Object.defineProperty(Ti,"__esModule",{value:true});Ti.DefaultAwsSecurityCredentialsSupplier=void 0;var _i=Pe();var ts=class{regionUrl;securityCredentialsUrl;imdsV2SessionTokenUrl;additionalGaxiosOptions;constructor(e){this.regionUrl=e.regionUrl;this.securityCredentialsUrl=e.securityCredentialsUrl;this.imdsV2SessionTokenUrl=e.imdsV2SessionTokenUrl;this.additionalGaxiosOptions=e.additionalGaxiosOptions}async getAwsRegion(e){if(this.#i){return this.#i}const n=new Headers;if(!this.#i&&this.imdsV2SessionTokenUrl){n.set("x-aws-ec2-metadata-token",await this.#e(e.transporter))}if(!this.regionUrl){throw new RangeError('Unable to determine AWS region due to missing "options.credential_source.region_url"')}const i={...this.additionalGaxiosOptions,url:this.regionUrl,method:"GET",responseType:"text",headers:n};_i.AuthClient.setMethodName(i,"getAwsRegion");const r=await e.transporter.request(i);return r.data.substr(0,r.data.length-1)}async getAwsSecurityCredentials(e){if(this.#r){return this.#r}const n=new Headers;if(this.imdsV2SessionTokenUrl){n.set("x-aws-ec2-metadata-token",await this.#e(e.transporter))}const i=await this.#t(n,e.transporter);const r=await this.#n(i,n,e.transporter);return{accessKeyId:r.AccessKeyId,secretAccessKey:r.SecretAccessKey,token:r.Token}}async#e(e){const n={...this.additionalGaxiosOptions,url:this.imdsV2SessionTokenUrl,method:"PUT",responseType:"text",headers:{"x-aws-ec2-metadata-token-ttl-seconds":"300"}};_i.AuthClient.setMethodName(n,"#getImdsV2SessionToken");const i=await e.request(n);return i.data}async#t(e,n){if(!this.securityCredentialsUrl){throw new Error('Unable to determine AWS role name due to missing "options.credential_source.url"')}const i={...this.additionalGaxiosOptions,url:this.securityCredentialsUrl,method:"GET",responseType:"text",headers:e};_i.AuthClient.setMethodName(i,"#getAwsRoleName");const r=await n.request(i);return r.data}async#n(e,n,i){const r={...this.additionalGaxiosOptions,url:`${this.securityCredentialsUrl}/${e}`,headers:n,responseType:"json"};_i.AuthClient.setMethodName(r,"#retrieveAwsSecurityCredentials");const o=await i.request(r);return o.data}get#i(){return process.env["AWS_REGION"]||process.env["AWS_DEFAULT_REGION"]||null}get#r(){if(process.env["AWS_ACCESS_KEY_ID"]&&process.env["AWS_SECRET_ACCESS_KEY"]){return{accessKeyId:process.env["AWS_ACCESS_KEY_ID"],secretAccessKey:process.env["AWS_SECRET_ACCESS_KEY"],token:process.env["AWS_SESSION_TOKEN"]}}return null}};Ti.DefaultAwsSecurityCredentialsSupplier=ts});var is=F(Ai=>{"use strict";Object.defineProperty(Ai,"__esModule",{value:true});Ai.AwsClient=void 0;var wm=es();var Rm=pt();var Pm=fc();var pc=qe();var Nm=ge();var ns=class t extends Rm.BaseExternalAccountClient{environmentId;awsSecurityCredentialsSupplier;regionalCredVerificationUrl;awsRequestSigner;region;static#e="https://sts.{region}.amazonaws.com?Action=GetCallerIdentity&Version=2011-06-15";static AWS_EC2_METADATA_IPV4_ADDRESS="169.254.169.254";static AWS_EC2_METADATA_IPV6_ADDRESS="fd00:ec2::254";constructor(e){super(e);const n=(0,pc.originalOrCamelOptions)(e);const i=n.get("credential_source");const r=n.get("aws_security_credentials_supplier");if(!i&&!r){throw new Error("A credential source or AWS security credentials supplier must be specified.")}if(i&&r){throw new Error("Only one of credential source or AWS security credentials supplier can be specified.")}if(r){this.awsSecurityCredentialsSupplier=r;this.regionalCredVerificationUrl=t.#e;this.credentialSourceType="programmatic"}else{const o=(0,pc.originalOrCamelOptions)(i);this.environmentId=o.get("environment_id");const l=o.get("region_url");const u=o.get("url");const c=o.get("imdsv2_session_token_url");this.awsSecurityCredentialsSupplier=new Pm.DefaultAwsSecurityCredentialsSupplier({regionUrl:l,securityCredentialsUrl:u,imdsV2SessionTokenUrl:c});this.regionalCredVerificationUrl=o.get("regional_cred_verification_url");this.credentialSourceType="aws";this.validateEnvironmentId()}this.awsRequestSigner=null;this.region=""}validateEnvironmentId(){const e=this.environmentId?.match(/^(aws)(\d+)$/);if(!e||!this.regionalCredVerificationUrl){throw new Error('No valid AWS "credential_source" provided')}else if(parseInt(e[2],10)!==1){throw new Error(`aws version "${e[2]}" is not supported in the current build.`)}}async retrieveSubjectToken(){if(!this.awsRequestSigner){this.region=await this.awsSecurityCredentialsSupplier.getAwsRegion(this.supplierContext);this.awsRequestSigner=new wm.AwsRequestSigner(async()=>{return this.awsSecurityCredentialsSupplier.getAwsSecurityCredentials(this.supplierContext)},this.region)}const e=await this.awsRequestSigner.getRequestOptions({...t.RETRY_CONFIG,url:this.regionalCredVerificationUrl.replace("{region}",this.region),method:"POST"});const n=[];const i=Nm.Gaxios.mergeHeaders({"x-goog-cloud-target-resource":this.audience},e.headers);i.forEach((r,o)=>n.push({key:o,value:r}));return encodeURIComponent(JSON.stringify({url:e.url,method:e.method,headers:n}))}};Ai.AwsClient=ns});var ls=F(de=>{"use strict";Object.defineProperty(de,"__esModule",{value:true});de.InvalidSubjectTokenError=de.InvalidMessageFieldError=de.InvalidCodeFieldError=de.InvalidTokenTypeFieldError=de.InvalidExpirationTimeFieldError=de.InvalidSuccessFieldError=de.InvalidVersionFieldError=de.ExecutableResponseError=de.ExecutableResponse=void 0;var Ci="urn:ietf:params:oauth:token-type:saml2";var rs="urn:ietf:params:oauth:token-type:id_token";var os="urn:ietf:params:oauth:token-type:jwt";var ss=class{version;success;expirationTime;tokenType;errorCode;errorMessage;subjectToken;constructor(e){if(!e.version){throw new vi("Executable response must contain a 'version' field.")}if(e.success===void 0){throw new Si("Executable response must contain a 'success' field.")}this.version=e.version;this.success=e.success;if(this.success){this.expirationTime=e.expiration_time;this.tokenType=e.token_type;if(this.tokenType!==Ci&&this.tokenType!==rs&&this.tokenType!==os){throw new Ii(`Executable response must contain a 'token_type' field when successful and it must be one of ${rs}, ${os}, or ${Ci}.`)}if(this.tokenType===Ci){if(!e.saml_response){throw new Tn(`Executable response must contain a 'saml_response' field when token_type=${Ci}.`)}this.subjectToken=e.saml_response}else{if(!e.id_token){throw new Tn(`Executable response must contain a 'id_token' field when token_type=${rs} or ${os}.`)}this.subjectToken=e.id_token}}else{if(!e.code){throw new wi("Executable response must contain a 'code' field when unsuccessful.")}if(!e.message){throw new Ri("Executable response must contain a 'message' field when unsuccessful.")}this.errorCode=e.code;this.errorMessage=e.message}}isValid(){return!this.isExpired()&&this.success}isExpired(){return this.expirationTime!==void 0&&this.expirationTime<Math.round(Date.now()/1e3)}};de.ExecutableResponse=ss;var et=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,new.target.prototype)}};de.ExecutableResponseError=et;var vi=class extends et{};de.InvalidVersionFieldError=vi;var Si=class extends et{};de.InvalidSuccessFieldError=Si;var as=class extends et{};de.InvalidExpirationTimeFieldError=as;var Ii=class extends et{};de.InvalidTokenTypeFieldError=Ii;var wi=class extends et{};de.InvalidCodeFieldError=wi;var Ri=class extends et{};de.InvalidMessageFieldError=Ri;var Tn=class extends et{};de.InvalidSubjectTokenError=Tn});var ds=F(Jt=>{"use strict";Object.defineProperty(Jt,"__esModule",{value:true});Jt.PluggableAuthHandler=Jt.ExecutableError=void 0;var Pt=ls();var Mm=z("child_process");var us=z("fs");var Pi=class extends Error{code;constructor(e,n){super(`The executable failed with exit code: ${n} and error message: ${e}.`);this.code=n;Object.setPrototypeOf(this,new.target.prototype)}};Jt.ExecutableError=Pi;var cs=class t{commandComponents;timeoutMillis;outputFile;constructor(e){if(!e.command){throw new Error("No command provided.")}this.commandComponents=t.parseCommand(e.command);this.timeoutMillis=e.timeoutMillis;if(!this.timeoutMillis){throw new Error("No timeoutMillis provided.")}this.outputFile=e.outputFile}retrieveResponseFromExecutable(e){return new Promise((n,i)=>{const r=Mm.spawn(this.commandComponents[0],this.commandComponents.slice(1),{env:{...process.env,...Object.fromEntries(e)}});let o="";r.stdout.on("data",u=>{o+=u});r.stderr.on("data",u=>{o+=u});const l=setTimeout(()=>{r.removeAllListeners();r.kill();return i(new Error("The executable failed to finish within the timeout specified."))},this.timeoutMillis);r.on("close",u=>{clearTimeout(l);if(u===0){try{const c=JSON.parse(o);const d=new Pt.ExecutableResponse(c);return n(d)}catch(c){if(c instanceof Pt.ExecutableResponseError){return i(c)}return i(new Pt.ExecutableResponseError(`The executable returned an invalid response: ${o}`))}}else{return i(new Pi(o,u.toString()))}})})}async retrieveCachedResponse(){if(!this.outputFile||this.outputFile.length===0){return void 0}let e;try{e=await us.promises.realpath(this.outputFile)}catch{return void 0}if(!(await us.promises.lstat(e)).isFile()){return void 0}const n=await us.promises.readFile(e,{encoding:"utf8"});if(n===""){return void 0}try{const i=JSON.parse(n);const r=new Pt.ExecutableResponse(i);if(r.isValid()){return new Pt.ExecutableResponse(i)}return void 0}catch(i){if(i instanceof Pt.ExecutableResponseError){throw i}throw new Pt.ExecutableResponseError(`The output file contained an invalid response: ${n}`)}}static parseCommand(e){const n=e.match(/(?:[^\s"]+|"[^"]*")+/g);if(!n){throw new Error(`Provided command: "${e}" could not be parsed.`)}for(let i=0;i<n.length;i++){if(n[i][0]==='"'&&n[i].slice(-1)==='"'){n[i]=n[i].slice(1,-1)}}return n}};Jt.PluggableAuthHandler=cs});var ps=F(Kt=>{"use strict";Object.defineProperty(Kt,"__esModule",{value:true});Kt.PluggableAuthClient=Kt.ExecutableError=void 0;var km=pt();var xm=ls();var hc=ds();var Dm=ds();Object.defineProperty(Kt,"ExecutableError",{enumerable:true,get:function(){return Dm.ExecutableError}});var Um=30*1e3;var gc=5*1e3;var mc=120*1e3;var Lm="GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES";var yc=1;var fs=class extends km.BaseExternalAccountClient{command;timeoutMillis;outputFile;handler;constructor(e){super(e);if(!e.credential_source.executable){throw new Error('No valid Pluggable Auth "credential_source" provided.')}this.command=e.credential_source.executable.command;if(!this.command){throw new Error('No valid Pluggable Auth "credential_source" provided.')}if(e.credential_source.executable.timeout_millis===void 0){this.timeoutMillis=Um}else{this.timeoutMillis=e.credential_source.executable.timeout_millis;if(this.timeoutMillis<gc||this.timeoutMillis>mc){throw new Error(`Timeout must be between ${gc} and ${mc} milliseconds.`)}}this.outputFile=e.credential_source.executable.output_file;this.handler=new hc.PluggableAuthHandler({command:this.command,timeoutMillis:this.timeoutMillis,outputFile:this.outputFile});this.credentialSourceType="executable"}async retrieveSubjectToken(){if(process.env[Lm]!=="1"){throw new Error("Pluggable Auth executables need to be explicitly allowed to run by setting the GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment Variable to 1.")}let e=void 0;if(this.outputFile){e=await this.handler.retrieveCachedResponse()}if(!e){const n=new Map;n.set("GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE",this.audience);n.set("GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE",this.subjectTokenType);n.set("GOOGLE_EXTERNAL_ACCOUNT_INTERACTIVE","0");if(this.outputFile){n.set("GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE",this.outputFile)}const i=this.getServiceAccountEmail();if(i){n.set("GOOGLE_EXTERNAL_ACCOUNT_IMPERSONATED_EMAIL",i)}e=await this.handler.retrieveResponseFromExecutable(n)}if(e.version>yc){throw new Error(`Version of executable is not currently supported, maximum supported version is ${yc}.`)}if(!e.success){throw new hc.ExecutableError(e.errorMessage,e.errorCode)}if(this.outputFile){if(!e.expirationTime){throw new xm.InvalidExpirationTimeFieldError("The executable response must contain the `expiration_time` field for successful responses when an output_file has been specified in the configuration.")}}if(e.isExpired()){throw new Error("Executable response is expired.")}return e.subjectToken}};Kt.PluggableAuthClient=fs});var gs=F(Ni=>{"use strict";Object.defineProperty(Ni,"__esModule",{value:true});Ni.ExternalAccountClient=void 0;var Gm=pt();var Om=Zo();var bm=is();var Fm=ps();var hs=class{constructor(){throw new Error("ExternalAccountClients should be initialized via: ExternalAccountClient.fromJSON(), directly via explicit constructors, eg. new AwsClient(options), new IdentityPoolClient(options), newPluggableAuthClientOptions, or via new GoogleAuth(options).getClient()")}static fromJSON(e){if(e&&e.type===Gm.EXTERNAL_ACCOUNT_TYPE){if(e.credential_source?.environment_id){return new bm.AwsClient(e)}else if(e.credential_source?.executable){return new Fm.PluggableAuthClient(e)}else{return new Om.IdentityPoolClient(e)}}else{return null}}};Ni.ExternalAccountClient=hs});var Es=F(Wt=>{"use strict";Object.defineProperty(Wt,"__esModule",{value:true});Wt.ExternalAccountAuthorizedUserClient=Wt.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=void 0;var _c=Pe();var Ec=qo();var Tc=ge();var qm=z("stream");var Hm=pt();Wt.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE="external_account_authorized_user";var Vm="https://sts.{universeDomain}/v1/oauthtoken";var ms=class t extends Ec.OAuthClientAuthHandler{#e;constructor(e){super(e);this.#e=e.tokenRefreshEndpoint}async refreshToken(e,n){const i={...t.RETRY_CONFIG,url:this.#e,method:"POST",headers:n,data:new URLSearchParams({grant_type:"refresh_token",refresh_token:e}),responseType:"json"};_c.AuthClient.setMethodName(i,"refreshToken");this.applyClientAuthenticationOptions(i);try{const r=await this.transporter.request(i);const o=r.data;o.res=r;return o}catch(r){if(r instanceof Tc.GaxiosError&&r.response){throw(0,Ec.getErrorFromOAuthErrorResponse)(r.response.data,r)}throw r}}};var ys=class extends _c.AuthClient{cachedAccessToken;externalAccountAuthorizedUserHandler;refreshToken;constructor(e){super(e);if(e.universe_domain){this.universeDomain=e.universe_domain}this.refreshToken=e.refresh_token;const n={confidentialClientType:"basic",clientId:e.client_id,clientSecret:e.client_secret};this.externalAccountAuthorizedUserHandler=new ms({tokenRefreshEndpoint:e.token_url??Vm.replace("{universeDomain}",this.universeDomain),transporter:this.transporter,clientAuthentication:n});this.cachedAccessToken=null;this.quotaProjectId=e.quota_project_id;if(typeof e?.eagerRefreshThresholdMillis!=="number"){this.eagerRefreshThresholdMillis=Hm.EXPIRATION_TIME_OFFSET}else{this.eagerRefreshThresholdMillis=e.eagerRefreshThresholdMillis}this.forceRefreshOnFailure=!!e?.forceRefreshOnFailure}async getAccessToken(){if(!this.cachedAccessToken||this.isExpired(this.cachedAccessToken)){await this.refreshAccessTokenAsync()}return{token:this.cachedAccessToken.access_token,res:this.cachedAccessToken.res}}async getRequestHeaders(){const e=await this.getAccessToken();const n=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(n)}request(e,n){if(n){this.requestAsync(e).then(i=>n(null,i),i=>{return n(i,i.response)})}else{return this.requestAsync(e)}}async requestAsync(e,n=false){let i;try{const r=await this.getRequestHeaders();e.headers=Tc.Gaxios.mergeHeaders(e.headers);this.addUserProjectAndAuthHeaders(e.headers,r);i=await this.transporter.request(e)}catch(r){const o=r.response;if(o){const l=o.status;const u=o.config.data instanceof qm.Readable;const c=l===401||l===403;if(!n&&c&&!u&&this.forceRefreshOnFailure){await this.refreshAccessTokenAsync();return await this.requestAsync(e,true)}}throw r}return i}async refreshAccessTokenAsync(){const e=await this.externalAccountAuthorizedUserHandler.refreshToken(this.refreshToken);this.cachedAccessToken={access_token:e.access_token,expiry_date:new Date().getTime()+e.expires_in*1e3,res:e.res};if(e.refresh_token!==void 0){this.refreshToken=e.refresh_token}return this.cachedAccessToken}isExpired(e){const n=new Date().getTime();return e.expiry_date?n>=e.expiry_date-this.eagerRefreshThresholdMillis:false}};Wt.ExternalAccountAuthorizedUserClient=ys});var Ts=F(ht=>{"use strict";Object.defineProperty(ht,"__esModule",{value:true});ht.GdchClient=ht.GDCH_SERVICE_ACCOUNT_TYPE=void 0;var Bm=z("crypto");var $m=z("fs");var Jm=z("https");var Km=ct();var Wm=3600;ht.GDCH_SERVICE_ACCOUNT_TYPE="gdch_service_account";var _s=class t extends Km.OAuth2Client{projectId;privateKeyId;privateKey;serviceIdentityName;tokenServerUri;caCertPath;apiAudience;lifetime;gdchOptions;caAgentPromise;cachedCaCertPath;lastCaCertReadTime=0;CA_CERT_TTL_MS=5*60*1e3;constructor(e={}){super(e);this.gdchOptions=e;this.projectId=e.projectId||void 0;this.privateKeyId=e.privateKeyId;this.privateKey=e.privateKey;this.serviceIdentityName=e.serviceIdentityName;this.tokenServerUri=e.tokenServerUri;this.caCertPath=e.caCertPath;this.apiAudience=e.apiAudience;this.lifetime=e.lifetime||Wm;this.credentials={refresh_token:"gdch-placeholder",expiry_date:1}}createWithGdchAudience(e){if(!e){throw new Error("Audience cannot be null or empty for GDCH service account credentials.")}return new t({...this.gdchOptions,projectId:this.projectId,privateKeyId:this.privateKeyId,privateKey:this.privateKey,serviceIdentityName:this.serviceIdentityName,tokenServerUri:this.tokenServerUri,caCertPath:this.caCertPath,lifetime:this.lifetime,apiAudience:e})}fromJSON(e){if(!e){throw new Error("Must pass in a JSON object containing the GDCH credentials settings.")}if(e.type!==ht.GDCH_SERVICE_ACCOUNT_TYPE){throw new Error(`The incoming JSON object does not have the "${ht.GDCH_SERVICE_ACCOUNT_TYPE}" type`)}if(e.format_version!=="1"){throw new Error("Only format version 1 is supported.")}if(!e.project){throw new Error("The incoming JSON object does not contain a project field")}if(!e.private_key_id){throw new Error("The incoming JSON object does not contain a private_key_id field")}if(!e.private_key){throw new Error("The incoming JSON object does not contain a private_key field")}if(!e.name){throw new Error("The incoming JSON object does not contain a name field")}if(!e.token_uri){throw new Error("The incoming JSON object does not contain a token_uri field")}this.projectId=e.project;this.privateKeyId=e.private_key_id;this.privateKey=e.private_key;this.serviceIdentityName=e.name;this.tokenServerUri=e.token_uri;this.caCertPath=e.ca_cert_path;this.gdchOptions={...this.gdchOptions,projectId:e.project,privateKeyId:e.private_key_id,privateKey:e.private_key,serviceIdentityName:e.name,tokenServerUri:e.token_uri,caCertPath:e.ca_cert_path}}async refreshTokenNoCache(){if(!this.apiAudience){throw new Error("Audience cannot be null or empty for GDCH service account credentials. Specify the audience by calling createWithGdchAudience.")}if(!this.privateKey){throw new Error("Private key is not configured for GDCH credentials.")}if(!this.privateKeyId){throw new Error("Private key ID is not configured for GDCH credentials.")}if(!this.projectId){throw new Error("Project is not configured for GDCH credentials.")}if(!this.serviceIdentityName){throw new Error("Service identity name is not configured for GDCH credentials.")}if(!this.tokenServerUri){throw new Error("Token server URI is not configured for GDCH credentials.")}const e=this.createAssertion();const n={audience:this.apiAudience,grant_type:"urn:ietf:params:oauth:token-type:token-exchange",requested_token_type:"urn:ietf:params:oauth:token-type:access_token",subject_token:e,subject_token_type:"urn:k8s:params:oauth:token-type:serviceaccount"};const i={url:this.tokenServerUri,method:"POST",headers:{"Content-Type":"application/json"},data:n,responseType:"json",timeout:1e4,retry:true,retryConfig:{httpMethodsToRetry:["POST"],statusCodesToRetry:[[500,599]],noResponseRetries:3}};if(this.caCertPath){i.agent=await this.getCaAgent()}try{const r=await this.transporter.request(i);const o=r.data;if(!o.access_token){throw new Error("Token response did not contain an access_token.")}if(!o.expires_in){throw new Error("Token response did not contain an expires_in field.")}const l={access_token:o.access_token,token_type:"STS-Bearer",expiry_date:Date.now()+o.expires_in*1e3};this.emit("tokens",l);return{res:r,tokens:l}}catch(r){if(r&&r.config&&r.config.data){try{if(typeof r.config.data==="string"){const o=JSON.parse(r.config.data);if(o.subject_token){o.subject_token="***REDACTED***";r.config.data=JSON.stringify(o)}}else if(typeof r.config.data==="object"&&r.config.data.subject_token){r.config.data.subject_token="***REDACTED***"}}catch{}}if(r instanceof Error){r.message=`Error getting access token for GDCH service account: ${r.message}, iss: ${this.serviceIdentityName}`}throw r}}createAssertion(){const e={alg:"ES256",typ:"JWT",kid:this.privateKeyId};const n=`system:serviceaccount:${this.projectId}:${this.serviceIdentityName}`;const i=Math.floor(Date.now()/1e3);const r={iss:n,sub:n,iat:i,exp:i+this.lifetime,aud:this.tokenServerUri};const o=this.base64UrlEncode(JSON.stringify(e));const l=this.base64UrlEncode(JSON.stringify(r));const u=`${o}.${l}`;const c=Bm.sign("sha256",Buffer.from(u),{key:this.privateKey,dsaEncoding:"ieee-p1363"});const d=this.base64UrlEncode(c);return`${u}.${d}`}async requestAsync(e,n=false){if(this.caCertPath&&!e.agent){const i=(e.url||"").toString();if(!i.includes("googleapis.com")&&!i.includes("google.com")){e.agent=await this.getCaAgent()}}return super.requestAsync(e,n)}getCaAgent(){if(!this.caCertPath){this.caAgentPromise=void 0;this.cachedCaCertPath=void 0;this.lastCaCertReadTime=0;return void 0}const e=Date.now();const n=e-this.lastCaCertReadTime>this.CA_CERT_TTL_MS;if(this.caAgentPromise&&this.caCertPath===this.cachedCaCertPath&&!n){return this.caAgentPromise}this.cachedCaCertPath=this.caCertPath;this.lastCaCertReadTime=e;const i=this.caCertPath;this.caAgentPromise=(async()=>{try{const r=await $m.promises.readFile(i);return new Jm.Agent({ca:r})}catch(r){if(this.cachedCaCertPath===i){this.caAgentPromise=void 0;this.cachedCaCertPath=void 0;this.lastCaCertReadTime=0}if(r instanceof Error){r.message=`Error reading certificate file from CA cert path, value '${i}': ${r.message}`}throw r}})();return this.caAgentPromise}toJSON(){return{...this,privateKey:this.privateKey?"***REDACTED***":void 0,_clientSecret:this._clientSecret?"***REDACTED***":void 0,apiKey:this.apiKey?"***REDACTED***":void 0,gdchOptions:this.gdchOptions?{...this.gdchOptions,privateKey:this.gdchOptions.privateKey?"***REDACTED***":void 0,clientSecret:this.gdchOptions.clientSecret?"***REDACTED***":void 0,client_secret:this.gdchOptions.client_secret?"***REDACTED***":void 0,apiKey:this.gdchOptions.apiKey?"***REDACTED***":void 0,credentials:this.gdchOptions.credentials?{...this.gdchOptions.credentials,access_token:this.gdchOptions.credentials.access_token?"***REDACTED***":void 0,refresh_token:this.gdchOptions.credentials.refresh_token?"***REDACTED***":void 0}:void 0}:void 0,credentials:{...this.credentials,access_token:this.credentials?.access_token?"***REDACTED***":void 0,refresh_token:this.credentials?.refresh_token?"***REDACTED***":void 0}}}[Symbol.for("nodejs.util.inspect.custom")](){return this.toJSON()}base64UrlEncode(e){const n=typeof e==="string"?Buffer.from(e):e;return n.toString("base64url")}};ht.GdchClient=_s});var Sc=F(Be=>{"use strict";Object.defineProperty(Be,"__esModule",{value:true});Be.GoogleAuth=Be.GoogleAuthExceptionMessages=void 0;var Ym=z("child_process");var An=z("fs");var zm=ge();var Cn=dn();var Xm=z("os");var Mi=z("path");var Qm=fn();var Zm=oo();var jm=ao();var ey=lo();var Yt=Uo();var Ac=Go();var zt=bo();var ty=gs();var vn=pt();var As=Pe();var Cc=Es();var Cs=Ts();var vc=qe();Be.GoogleAuthExceptionMessages={API_KEY_WITH_CREDENTIALS:"API Keys and Credentials are mutually exclusive authentication methods and cannot be used together.",NO_PROJECT_ID_FOUND:"Unable to detect a Project Id in the current environment. \nTo learn more about authentication and Google APIs, visit: \nhttps://cloud.google.com/docs/authentication/getting-started",NO_CREDENTIALS_FOUND:"Unable to find credentials in current environment. \nTo learn more about authentication and Google APIs, visit: \nhttps://cloud.google.com/docs/authentication/getting-started",NO_ADC_FOUND:"Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.",NO_UNIVERSE_DOMAIN_FOUND:"Unable to detect a Universe Domain in the current environment.\nTo learn more about Universe Domain retrieval, visit: \nhttps://cloud.google.com/compute/docs/metadata/predefined-metadata-keys"};var vs=class{checkIsGCE=void 0;useJWTAccessWithScope;defaultServicePath;get isGCE(){return this.checkIsGCE}_findProjectIdPromise;_cachedProjectId;jsonContent=null;apiKey;cachedCredential=null;#e=null;defaultScopes;keyFilename;scopes;clientOptions={};constructor(e={}){this._cachedProjectId=e.projectId||null;this.cachedCredential=e.authClient||null;this.keyFilename=e.keyFilename||e.keyFile;this.scopes=e.scopes;this.clientOptions=e.clientOptions||{};this.jsonContent=e.credentials||null;this.apiKey=e.apiKey||this.clientOptions.apiKey||null;if(this.apiKey&&(this.jsonContent||this.clientOptions.credentials)){throw new RangeError(Be.GoogleAuthExceptionMessages.API_KEY_WITH_CREDENTIALS)}if(e.universeDomain){this.clientOptions.universeDomain=e.universeDomain}}setGapicJWTValues(e){e.defaultServicePath=this.defaultServicePath;e.useJWTAccessWithScope=this.useJWTAccessWithScope;e.defaultScopes=this.defaultScopes}getProjectId(e){if(e){this.getProjectIdAsync().then(n=>e(null,n),e)}else{return this.getProjectIdAsync()}}async getProjectIdOptional(){try{return await this.getProjectId()}catch(e){if(e instanceof Error&&e.message===Be.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND){return null}else{throw e}}}async findAndCacheProjectId(){let e=null;e||=await this.getProductionProjectId();e||=await this.getFileProjectId();e||=await this.getDefaultServiceProjectId();e||=await this.getGCEProjectId();e||=await this.getExternalAccountClientProjectId();if(e){this._cachedProjectId=e;return e}else{throw new Error(Be.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND)}}async getProjectIdAsync(){if(this._cachedProjectId){return this._cachedProjectId}if(!this._findProjectIdPromise){this._findProjectIdPromise=this.findAndCacheProjectId()}return this._findProjectIdPromise}async getUniverseDomainFromMetadataServer(){let e;try{e=await Cn.universe("universe-domain");e||=As.DEFAULT_UNIVERSE}catch(n){if(n&&n?.response?.status===404){e=As.DEFAULT_UNIVERSE}else{throw n}}return e}async getUniverseDomain(){let e=(0,vc.originalOrCamelOptions)(this.clientOptions).get("universe_domain");try{e??=(await this.getClient()).universeDomain}catch{e??=As.DEFAULT_UNIVERSE}return e}getAnyScopes(){return this.scopes||this.defaultScopes}getApplicationDefault(e={},n){let i;if(typeof e==="function"){n=e}else{i=e}if(n){this.getApplicationDefaultAsync(i).then(r=>n(null,r.credential,r.projectId),n)}else{return this.getApplicationDefaultAsync(i)}}async getApplicationDefaultAsync(e={}){if(this.cachedCredential){return await this.#t(this.cachedCredential,null)}let n;n=await this._tryGetApplicationCredentialsFromEnvironmentVariable(e);if(n){if(n instanceof Yt.JWT){n.scopes=this.scopes}else if(n instanceof vn.BaseExternalAccountClient){n.scopes=this.getAnyScopes()}return await this.#t(n)}n=await this._tryGetApplicationCredentialsFromWellKnownFile(e);if(n){if(n instanceof Yt.JWT){n.scopes=this.scopes}else if(n instanceof vn.BaseExternalAccountClient){n.scopes=this.getAnyScopes()}return await this.#t(n)}if(await this._checkIsGCE()){e.scopes=this.getAnyScopes();return await this.#t(new Zm.Compute(e))}throw new Error(Be.GoogleAuthExceptionMessages.NO_ADC_FOUND)}async#t(e,n=process.env["GOOGLE_CLOUD_QUOTA_PROJECT"]||null){const i=await this.getProjectIdOptional();if(n){e.quotaProjectId=n}this.cachedCredential=e;return{credential:e,projectId:i}}async _checkIsGCE(){if(this.checkIsGCE===void 0){this.checkIsGCE=Cn.getGCPResidency()||await Cn.isAvailable()}return this.checkIsGCE}async _tryGetApplicationCredentialsFromEnvironmentVariable(e){const n=process.env["GOOGLE_APPLICATION_CREDENTIALS"]||process.env["google_application_credentials"];if(!n||n.length===0){return null}try{return await this._getApplicationCredentialsFromFilePath(n,e)}catch(i){if(i instanceof Error){i.message=`Unable to read the credential file specified by the GOOGLE_APPLICATION_CREDENTIALS environment variable: ${i.message}`}throw i}}async _tryGetApplicationCredentialsFromWellKnownFile(e){let n=process.env["CLOUDSDK_CONFIG"];if(!n){if(this._isWindows()){if(process.env["APPDATA"]){n=Mi.join(process.env["APPDATA"],"gcloud")}}else{const o=process.env["HOME"];if(o){n=Mi.join(o,".config","gcloud")}}}if(!n){return null}const i=Mi.join(n,"application_default_credentials.json");if(!An.existsSync(i)){return null}const r=await this._getApplicationCredentialsFromFilePath(i,e);return r}async _getApplicationCredentialsFromFilePath(e,n={}){if(!e||e.length===0){throw new Error("The file path is invalid.")}try{e=An.realpathSync(e);if(!An.lstatSync(e).isFile()){throw new Error}}catch(r){if(r instanceof Error){r.message=`The file at ${e} does not exist, or it is not a file. ${r.message}`}throw r}const i=An.createReadStream(e);return this.fromStream(i,n)}fromImpersonatedJSON(e){if(!e){throw new Error("Must pass in a JSON object containing an impersonated refresh token")}if(e.type!==zt.IMPERSONATED_ACCOUNT_TYPE){throw new Error(`The incoming JSON object does not have the "${zt.IMPERSONATED_ACCOUNT_TYPE}" type`)}if(!e.source_credentials){throw new Error("The incoming JSON object does not contain a source_credentials field")}if(!e.service_account_impersonation_url){throw new Error("The incoming JSON object does not contain a service_account_impersonation_url field")}const n=this.fromJSON(e.source_credentials);if(e.service_account_impersonation_url?.length>256){throw new RangeError(`Target principal is too long: ${e.service_account_impersonation_url}`)}const i=/(?<target>[^/]+):(generateAccessToken|generateIdToken)$/.exec(e.service_account_impersonation_url)?.groups?.target;if(!i){throw new RangeError(`Cannot extract target principal from ${e.service_account_impersonation_url}`)}const r=(this.scopes||e.scopes||this.defaultScopes)??[];return new zt.Impersonated({...e,sourceClient:n,targetPrincipal:i,targetScopes:Array.isArray(r)?r:[r]})}fromJSON(e,n={}){let i;const r=(0,vc.originalOrCamelOptions)(n).get("universe_domain");if(e.type===Ac.USER_REFRESH_ACCOUNT_TYPE){i=new Ac.UserRefreshClient(n);i.fromJSON(e)}else if(e.type===zt.IMPERSONATED_ACCOUNT_TYPE){i=this.fromImpersonatedJSON(e)}else if(e.type===vn.EXTERNAL_ACCOUNT_TYPE){i=ty.ExternalAccountClient.fromJSON({...e,...n});i.scopes=this.getAnyScopes()}else if(e.type===Cc.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE){i=new Cc.ExternalAccountAuthorizedUserClient({...e,...n})}else if(e.type===Cs.GDCH_SERVICE_ACCOUNT_TYPE){i=new Cs.GdchClient(n);i.fromJSON(e)}else{n.scopes=this.scopes;i=new Yt.JWT(n);this.setGapicJWTValues(i);i.fromJSON(e)}if(r){i.universeDomain=r}return i}_cacheClientFromJSON(e,n){const i=this.fromJSON(e,n);this.jsonContent=e;this.cachedCredential=i;return i}fromStream(e,n={},i){let r={};if(typeof n==="function"){i=n}else{r=n}if(i){this.fromStreamAsync(e,r).then(o=>i(null,o),i)}else{return this.fromStreamAsync(e,r)}}fromStreamAsync(e,n){return new Promise((i,r)=>{if(!e){throw new Error("Must pass in a stream containing the Google auth settings.")}const o=[];e.setEncoding("utf8").on("error",r).on("data",l=>o.push(l)).on("end",()=>{try{try{const l=JSON.parse(o.join(""));const u=this._cacheClientFromJSON(l,n);return i(u)}catch(l){if(!this.keyFilename)throw l;const u=new Yt.JWT({...this.clientOptions,keyFile:this.keyFilename});this.cachedCredential=u;this.setGapicJWTValues(u);return i(u)}}catch(l){return r(l)}})})}fromAPIKey(e,n={}){return new Yt.JWT({...n,apiKey:e})}_isWindows(){const e=Xm.platform();if(e&&e.length>=3){if(e.substring(0,3).toLowerCase()==="win"){return true}}return false}async getDefaultServiceProjectId(){return new Promise(e=>{(0,Ym.exec)("gcloud config config-helper --format json",(n,i)=>{if(!n&&i){try{const r=JSON.parse(i).configuration.properties.core.project;e(r);return}catch(r){}}e(null)})})}getProductionProjectId(){return process.env["GCLOUD_PROJECT"]||process.env["GOOGLE_CLOUD_PROJECT"]||process.env["gcloud_project"]||process.env["google_cloud_project"]}async getFileProjectId(){if(this.cachedCredential){return this.cachedCredential.projectId}if(this.keyFilename){const n=await this.getClient();if(n&&n.projectId){return n.projectId}}const e=await this._tryGetApplicationCredentialsFromEnvironmentVariable();if(e){return e.projectId}else{return null}}async getExternalAccountClientProjectId(){if(!this.jsonContent||this.jsonContent.type!==vn.EXTERNAL_ACCOUNT_TYPE){return null}const e=await this.getClient();return await e.getProjectId()}async getGCEProjectId(){try{const e=await Cn.project("project-id");return e}catch(e){return null}}getCredentials(e){if(e){this.getCredentialsAsync().then(n=>e(null,n),e)}else{return this.getCredentialsAsync()}}async getCredentialsAsync(){const e=await this.getClient();if(e instanceof zt.Impersonated){return{client_email:e.getTargetPrincipal()}}if(e instanceof vn.BaseExternalAccountClient){const n=e.getServiceAccountEmail();if(n){return{client_email:n,universe_domain:e.universeDomain}}}if(this.jsonContent){return{client_email:this.jsonContent.client_email,private_key:this.jsonContent.private_key,universe_domain:this.jsonContent.universe_domain}}if(await this._checkIsGCE()){const[n,i]=await Promise.all([Cn.instance("service-accounts/default/email"),this.getUniverseDomain()]);return{client_email:n,universe_domain:i}}throw new Error(Be.GoogleAuthExceptionMessages.NO_CREDENTIALS_FOUND)}async getClient(){if(this.cachedCredential){return this.cachedCredential}this.#e=this.#e||this.#n();try{const e=await this.#e;if(e instanceof Cs.GdchClient&&!e.apiAudience){const n=this.clientOptions;const i=n.apiEndpoint||n.servicePath;if(i){const r=i.startsWith("http")?"":"https://";const o=`${r}${i}`.replace(/\/+$/,"");const l=e.createWithGdchAudience(o);this.cachedCredential=l;return l}}return e}finally{this.#e=null}}async#n(){if(this.jsonContent){return this._cacheClientFromJSON(this.jsonContent,this.clientOptions)}else if(this.keyFilename){const e=Mi.resolve(this.keyFilename);const n=An.createReadStream(e);return await this.fromStreamAsync(n,this.clientOptions)}else if(this.apiKey){const e=await this.fromAPIKey(this.apiKey,this.clientOptions);e.scopes=this.scopes;const{credential:n}=await this.#t(e);return n}else{const{credential:e}=await this.getApplicationDefaultAsync(this.clientOptions);return e}}async getIdTokenClient(e){const n=await this.getClient();if(!("fetchIdToken"in n)){throw new Error("Cannot fetch ID token in this environment, use GCE or set the GOOGLE_APPLICATION_CREDENTIALS environment variable to a service account credentials JSON file.")}return new jm.IdTokenClient({targetAudience:e,idTokenProvider:n})}async getAccessToken(){const e=await this.getClient();return(await e.getAccessToken()).token}async getRequestHeaders(e){const n=await this.getClient();return n.getRequestHeaders(e)}async authorizeRequest(e={}){const n=e.url;const i=await this.getClient();const r=await i.getRequestHeaders(n);e.headers=zm.Gaxios.mergeHeaders(e.headers,r);return e}async fetch(...e){const n=await this.getClient();return n.fetch(...e)}async request(e){const n=await this.getClient();return n.request(e)}getEnv(){return(0,ey.getEnv)()}async sign(e,n){const i=await this.getClient();const r=await this.getUniverseDomain();n=n||`https://iamcredentials.${r}/v1/projects/-/serviceAccounts/`;if(i instanceof zt.Impersonated){const u=await i.sign(e);return u.signedBlob}const o=(0,Qm.createCrypto)();if(i instanceof Yt.JWT&&i.key){const u=await o.sign(i.key,e);return u}const l=await this.getCredentials();if(!l.client_email){throw new Error("Cannot sign data without `client_email`.")}return this.signBlob(o,l.client_email,e,n)}async signBlob(e,n,i,r){const o=new URL(r+`${n}:signBlob`);const l=await this.request({method:"POST",url:o.href,data:{payload:e.encodeBase64StringUtf8(i)},retry:true,retryConfig:{httpMethodsToRetry:["POST"]}});return l.data.signedBlob}};Be.GoogleAuth=vs});var Ic=F(ki=>{"use strict";Object.defineProperty(ki,"__esModule",{value:true});ki.IAMAuth=void 0;var Ss=class{selector;token;constructor(e,n){this.selector=e;this.token=n;this.selector=e;this.token=n}getRequestHeaders(){return{"x-goog-iam-authority-selector":this.selector,"x-goog-iam-authorization-token":this.token}}};ki.IAMAuth=Ss});var wc=F(tt=>{"use strict";Object.defineProperty(tt,"__esModule",{value:true});tt.DownscopedClient=tt.EXPIRATION_TIME_OFFSET=tt.MAX_ACCESS_BOUNDARY_RULES_COUNT=void 0;var ny=ge();var iy=z("stream");var Is=Pe();var ry=ci();var oy="urn:ietf:params:oauth:grant-type:token-exchange";var sy="urn:ietf:params:oauth:token-type:access_token";var ay="urn:ietf:params:oauth:token-type:access_token";tt.MAX_ACCESS_BOUNDARY_RULES_COUNT=10;tt.EXPIRATION_TIME_OFFSET=5*60*1e3;var ws=class extends Is.AuthClient{authClient;credentialAccessBoundary;cachedDownscopedAccessToken;stsCredential;constructor(e,n={accessBoundary:{accessBoundaryRules:[]}}){super(e instanceof Is.AuthClient?{}:e);if(e instanceof Is.AuthClient){this.authClient=e;this.credentialAccessBoundary=n}else{this.authClient=e.authClient;this.credentialAccessBoundary=e.credentialAccessBoundary}if(this.credentialAccessBoundary.accessBoundary.accessBoundaryRules.length===0){throw new Error("At least one access boundary rule needs to be defined.")}else if(this.credentialAccessBoundary.accessBoundary.accessBoundaryRules.length>tt.MAX_ACCESS_BOUNDARY_RULES_COUNT){throw new Error(`The provided access boundary has more than ${tt.MAX_ACCESS_BOUNDARY_RULES_COUNT} access boundary rules.`)}for(const i of this.credentialAccessBoundary.accessBoundary.accessBoundaryRules){if(i.availablePermissions.length===0){throw new Error("At least one permission should be defined in access boundary rules.")}}this.stsCredential=new ry.StsCredentials({tokenExchangeEndpoint:`https://sts.${this.universeDomain}/v1/token`});this.cachedDownscopedAccessToken=null}setCredentials(e){if(!e.expiry_date){throw new Error("The access token expiry_date field is missing in the provided credentials.")}super.setCredentials(e);this.cachedDownscopedAccessToken=e}async getAccessToken(){if(!this.cachedDownscopedAccessToken||this.isExpired(this.cachedDownscopedAccessToken)){await this.refreshAccessTokenAsync()}return{token:this.cachedDownscopedAccessToken.access_token,expirationTime:this.cachedDownscopedAccessToken.expiry_date,res:this.cachedDownscopedAccessToken.res}}async getRequestHeaders(){const e=await this.getAccessToken();const n=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(n)}request(e,n){if(n){this.requestAsync(e).then(i=>n(null,i),i=>{return n(i,i.response)})}else{return this.requestAsync(e)}}async requestAsync(e,n=false){let i;try{const r=await this.getRequestHeaders();e.headers=ny.Gaxios.mergeHeaders(e.headers);this.addUserProjectAndAuthHeaders(e.headers,r);i=await this.transporter.request(e)}catch(r){const o=r.response;if(o){const l=o.status;const u=o.config.data instanceof iy.Readable;const c=l===401||l===403;if(!n&&c&&!u&&this.forceRefreshOnFailure){await this.refreshAccessTokenAsync();return await this.requestAsync(e,true)}}throw r}return i}async refreshAccessTokenAsync(){const e=(await this.authClient.getAccessToken()).token;const n={grantType:oy,requestedTokenType:sy,subjectToken:e,subjectTokenType:ay};const i=await this.stsCredential.exchangeToken(n,void 0,this.credentialAccessBoundary);const r=this.authClient.credentials?.expiry_date||null;const o=i.expires_in?new Date().getTime()+i.expires_in*1e3:r;this.cachedDownscopedAccessToken={access_token:i.access_token,expiry_date:o,res:i.res};this.credentials={};Object.assign(this.credentials,this.cachedDownscopedAccessToken);delete this.credentials.res;this.emit("tokens",{refresh_token:null,expiry_date:this.cachedDownscopedAccessToken.expiry_date,access_token:this.cachedDownscopedAccessToken.access_token,token_type:"Bearer",id_token:null});return this.cachedDownscopedAccessToken}isExpired(e){const n=new Date().getTime();return e.expiry_date?n>=e.expiry_date-this.eagerRefreshThresholdMillis:false}};tt.DownscopedClient=ws});var Rc=F(xi=>{"use strict";Object.defineProperty(xi,"__esModule",{value:true});xi.PassThroughClient=void 0;var ly=Pe();var Rs=class extends ly.AuthClient{async request(e){return this.transporter.request(e)}async getAccessToken(){return{}}async getRequestHeaders(){return new Headers}};xi.PassThroughClient=Rs});var Dc=F(B=>{"use strict";var uy=B&&B.__createBinding||(Object.create?(function(t,e,n,i){if(i===void 0)i=n;var r=Object.getOwnPropertyDescriptor(e,n);if(!r||("get"in r?!e.__esModule:r.writable||r.configurable)){r={enumerable:true,get:function(){return e[n]}}}Object.defineProperty(t,i,r)}):(function(t,e,n,i){if(i===void 0)i=n;t[i]=e[n]}));var cy=B&&B.__exportStar||function(t,e){for(var n in t)if(n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n))uy(e,t,n)};Object.defineProperty(B,"__esModule",{value:true});B.GoogleAuth=B.auth=B.GDCH_SERVICE_ACCOUNT_TYPE=B.GdchClient=B.PassThroughClient=B.ExternalAccountAuthorizedUserClient=B.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=B.ExecutableError=B.PluggableAuthClient=B.DownscopedClient=B.BaseExternalAccountClient=B.ExternalAccountClient=B.IdentityPoolClient=B.AwsRequestSigner=B.AwsClient=B.UserRefreshClient=B.LoginTicket=B.ClientAuthentication=B.OAuth2Client=B.CodeChallengeMethod=B.Impersonated=B.JWT=B.JWTAccess=B.IdTokenClient=B.IAMAuth=B.GCPEnv=B.Compute=B.DEFAULT_UNIVERSE=B.AuthClient=B.gaxios=B.gcpMetadata=void 0;var Pc=Sc();Object.defineProperty(B,"GoogleAuth",{enumerable:true,get:function(){return Pc.GoogleAuth}});B.gcpMetadata=dn();B.gaxios=ge();var Nc=Pe();Object.defineProperty(B,"AuthClient",{enumerable:true,get:function(){return Nc.AuthClient}});Object.defineProperty(B,"DEFAULT_UNIVERSE",{enumerable:true,get:function(){return Nc.DEFAULT_UNIVERSE}});var dy=oo();Object.defineProperty(B,"Compute",{enumerable:true,get:function(){return dy.Compute}});var fy=lo();Object.defineProperty(B,"GCPEnv",{enumerable:true,get:function(){return fy.GCPEnv}});var py=Ic();Object.defineProperty(B,"IAMAuth",{enumerable:true,get:function(){return py.IAMAuth}});var hy=ao();Object.defineProperty(B,"IdTokenClient",{enumerable:true,get:function(){return hy.IdTokenClient}});var gy=xo();Object.defineProperty(B,"JWTAccess",{enumerable:true,get:function(){return gy.JWTAccess}});var my=Uo();Object.defineProperty(B,"JWT",{enumerable:true,get:function(){return my.JWT}});var yy=bo();Object.defineProperty(B,"Impersonated",{enumerable:true,get:function(){return yy.Impersonated}});var Ps=ct();Object.defineProperty(B,"CodeChallengeMethod",{enumerable:true,get:function(){return Ps.CodeChallengeMethod}});Object.defineProperty(B,"OAuth2Client",{enumerable:true,get:function(){return Ps.OAuth2Client}});Object.defineProperty(B,"ClientAuthentication",{enumerable:true,get:function(){return Ps.ClientAuthentication}});var Ey=to();Object.defineProperty(B,"LoginTicket",{enumerable:true,get:function(){return Ey.LoginTicket}});var _y=Go();Object.defineProperty(B,"UserRefreshClient",{enumerable:true,get:function(){return _y.UserRefreshClient}});var Ty=is();Object.defineProperty(B,"AwsClient",{enumerable:true,get:function(){return Ty.AwsClient}});var Ay=es();Object.defineProperty(B,"AwsRequestSigner",{enumerable:true,get:function(){return Ay.AwsRequestSigner}});var Cy=Zo();Object.defineProperty(B,"IdentityPoolClient",{enumerable:true,get:function(){return Cy.IdentityPoolClient}});var vy=gs();Object.defineProperty(B,"ExternalAccountClient",{enumerable:true,get:function(){return vy.ExternalAccountClient}});var Sy=pt();Object.defineProperty(B,"BaseExternalAccountClient",{enumerable:true,get:function(){return Sy.BaseExternalAccountClient}});var Iy=wc();Object.defineProperty(B,"DownscopedClient",{enumerable:true,get:function(){return Iy.DownscopedClient}});var Mc=ps();Object.defineProperty(B,"PluggableAuthClient",{enumerable:true,get:function(){return Mc.PluggableAuthClient}});Object.defineProperty(B,"ExecutableError",{enumerable:true,get:function(){return Mc.ExecutableError}});var kc=Es();Object.defineProperty(B,"EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE",{enumerable:true,get:function(){return kc.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE}});Object.defineProperty(B,"ExternalAccountAuthorizedUserClient",{enumerable:true,get:function(){return kc.ExternalAccountAuthorizedUserClient}});var wy=Rc();Object.defineProperty(B,"PassThroughClient",{enumerable:true,get:function(){return wy.PassThroughClient}});var xc=Ts();Object.defineProperty(B,"GdchClient",{enumerable:true,get:function(){return xc.GdchClient}});Object.defineProperty(B,"GDCH_SERVICE_ACCOUNT_TYPE",{enumerable:true,get:function(){return xc.GDCH_SERVICE_ACCOUNT_TYPE}});cy(Mo(),B);var Ry=new Pc.GoogleAuth;B.auth=Ry});var hr=$a(ja(),1);var pf=$a(Dc(),1);import{createWriteStream as Py}from"fs";import*as gr from"fs/promises";import{writeFile as Ny}from"fs/promises";import{Readable as My}from"node:stream";import{finished as ky}from"node:stream/promises";import*as hf from"path";var xy=void 0;var Dy=void 0;function Uy(){return{geminiUrl:xy,vertexUrl:Dy}}function Ly(t,e,n,i){var r,o;if(!(t===null||t===void 0?void 0:t.baseUrl)){const l=Uy();if(e){return(r=l.vertexUrl)!==null&&r!==void 0?r:n}else{return(o=l.geminiUrl)!==null&&o!==void 0?o:i}}return t.baseUrl}var We=class{};function H(t,e){const n=/\{([^}]+)\}/g;return t.replace(n,(i,r)=>{if(Object.prototype.hasOwnProperty.call(e,r)){const o=e[r];return o!==void 0&&o!==null?String(o):""}else{throw new Error(`Key '${r}' not found in valueMap.`)}})}function a(t,e,n){for(let o=0;o<e.length-1;o++){const l=e[o];if(l.endsWith("[]")){const u=l.slice(0,-2);if(!(u in t)){if(Array.isArray(n)){t[u]=Array.from({length:n.length},()=>({}))}else{throw new Error(`Value must be a list given an array path ${l}`)}}if(Array.isArray(t[u])){const c=t[u];if(Array.isArray(n)){for(let d=0;d<c.length;d++){const f=c[d];a(f,e.slice(o+1),n[d])}}else{for(const d of c){a(d,e.slice(o+1),n)}}}return}else if(l.endsWith("[0]")){const u=l.slice(0,-3);if(!(u in t)){t[u]=[{}]}const c=t[u];a(c[0],e.slice(o+1),n);return}if(!t[l]||typeof t[l]!=="object"){t[l]={}}t=t[l]}const i=e[e.length-1];const r=t[i];if(r!==void 0){if(!n||typeof n==="object"&&Object.keys(n).length===0){return}if(n===r){return}if(typeof r==="object"&&typeof n==="object"&&r!==null&&n!==null){Object.assign(r,n)}else{throw new Error(`Cannot set value for an existing key. Key: ${i}`)}}else{if(i==="_self"&&typeof n==="object"&&n!==null&&!Array.isArray(n)){const o=n;Object.assign(t,o)}else{t[i]=n}}}function s(t,e,n=void 0){try{if(e.length===1&&e[0]==="_self"){return t}for(let i=0;i<e.length;i++){if(typeof t!=="object"||t===null){return n}const r=e[i];if(r.endsWith("[]")){const o=r.slice(0,-2);if(o in t){const l=t[o];if(!Array.isArray(l)){return n}return l.map(u=>s(u,e.slice(i+1),n))}else{return n}}else{t=t[r]}}return t}catch(i){if(i instanceof TypeError){return n}throw i}}function Gy(t,e){for(const[n,i]of Object.entries(e)){const r=n.split(".");const o=i.split(".");const l=new Set;let u=-1;for(let c=0;c<r.length;c++){if(r[c]==="*"){u=c;break}}if(u!==-1&&o.length>u){for(let c=u;c<o.length;c++){const d=o[c];if(d!=="*"&&!d.endsWith("[]")&&!d.endsWith("[0]")){l.add(d)}}}xs(t,r,o,0,l)}}function xs(t,e,n,i,r){if(i>=e.length){return}if(typeof t!=="object"||t===null){return}const o=e[i];if(o.endsWith("[]")){const l=o.slice(0,-2);const u=t;if(l in u&&Array.isArray(u[l])){for(const c of u[l]){xs(c,e,n,i+1,r)}}}else if(o==="*"){if(typeof t==="object"&&t!==null&&!Array.isArray(t)){const l=t;const u=Object.keys(l).filter(d=>!d.startsWith("_")&&!r.has(d));const c={};for(const d of u){c[d]=l[d]}for(const[d,f]of Object.entries(c)){const p=[];for(const h of n.slice(i)){if(h==="*"){p.push(d)}else{p.push(h)}}a(l,p,f)}for(const d of u){delete l[d]}}}else{const l=t;if(o in l){xs(l[o],e,n,i+1,r)}}}function Da(t){if(typeof t!=="string"){throw new Error("fromImageBytes must be a string")}return t}function Oy(t){const e={};const n=s(t,["operationName"]);if(n!=null){a(e,["operationName"],n)}const i=s(t,["resourceName"]);if(i!=null){a(e,["_url","resourceName"],i)}return e}function by(t){const e={};const n=s(t,["name"]);if(n!=null){a(e,["name"],n)}const i=s(t,["metadata"]);if(i!=null){a(e,["metadata"],i)}const r=s(t,["done"]);if(r!=null){a(e,["done"],r)}const o=s(t,["error"]);if(o!=null){a(e,["error"],o)}const l=s(t,["response","generateVideoResponse"]);if(l!=null){a(e,["response"],qy(l))}return e}function Fy(t){const e={};const n=s(t,["name"]);if(n!=null){a(e,["name"],n)}const i=s(t,["metadata"]);if(i!=null){a(e,["metadata"],i)}const r=s(t,["done"]);if(r!=null){a(e,["done"],r)}const o=s(t,["error"]);if(o!=null){a(e,["error"],o)}const l=s(t,["response"]);if(l!=null){a(e,["response"],Hy(l))}return e}function qy(t){const e={};const n=s(t,["generatedSamples"]);if(n!=null){let o=n;if(Array.isArray(o)){o=o.map(l=>{return Vy(l)})}a(e,["generatedVideos"],o)}const i=s(t,["raiMediaFilteredCount"]);if(i!=null){a(e,["raiMediaFilteredCount"],i)}const r=s(t,["raiMediaFilteredReasons"]);if(r!=null){a(e,["raiMediaFilteredReasons"],r)}return e}function Hy(t){const e={};const n=s(t,["videos"]);if(n!=null){let o=n;if(Array.isArray(o)){o=o.map(l=>{return By(l)})}a(e,["generatedVideos"],o)}const i=s(t,["raiMediaFilteredCount"]);if(i!=null){a(e,["raiMediaFilteredCount"],i)}const r=s(t,["raiMediaFilteredReasons"]);if(r!=null){a(e,["raiMediaFilteredReasons"],r)}return e}function Vy(t){const e={};const n=s(t,["video"]);if(n!=null){a(e,["video"],zy(n))}return e}function By(t){const e={};const n=s(t,["_self"]);if(n!=null){a(e,["video"],Xy(n))}return e}function $y(t){const e={};const n=s(t,["operationName"]);if(n!=null){a(e,["_url","operationName"],n)}return e}function Jy(t){const e={};const n=s(t,["operationName"]);if(n!=null){a(e,["_url","operationName"],n)}return e}function Ky(t){const e={};const n=s(t,["name"]);if(n!=null){a(e,["name"],n)}const i=s(t,["metadata"]);if(i!=null){a(e,["metadata"],i)}const r=s(t,["done"]);if(r!=null){a(e,["done"],r)}const o=s(t,["error"]);if(o!=null){a(e,["error"],o)}const l=s(t,["response"]);if(l!=null){a(e,["response"],Wy(l))}return e}function Wy(t){const e={};const n=s(t,["sdkHttpResponse"]);if(n!=null){a(e,["sdkHttpResponse"],n)}const i=s(t,["parent"]);if(i!=null){a(e,["parent"],i)}const r=s(t,["documentName"]);if(r!=null){a(e,["documentName"],r)}return e}function Ua(t){const e={};const n=s(t,["name"]);if(n!=null){a(e,["name"],n)}const i=s(t,["metadata"]);if(i!=null){a(e,["metadata"],i)}const r=s(t,["done"]);if(r!=null){a(e,["done"],r)}const o=s(t,["error"]);if(o!=null){a(e,["error"],o)}const l=s(t,["response"]);if(l!=null){a(e,["response"],Yy(l))}return e}function Yy(t){const e={};const n=s(t,["sdkHttpResponse"]);if(n!=null){a(e,["sdkHttpResponse"],n)}const i=s(t,["parent"]);if(i!=null){a(e,["parent"],i)}const r=s(t,["documentName"]);if(r!=null){a(e,["documentName"],r)}return e}function zy(t){const e={};const n=s(t,["uri"]);if(n!=null){a(e,["uri"],n)}const i=s(t,["encodedVideo"]);if(i!=null){a(e,["videoBytes"],Da(i))}const r=s(t,["encoding"]);if(r!=null){a(e,["mimeType"],r)}return e}function Xy(t){const e={};const n=s(t,["gcsUri"]);if(n!=null){a(e,["uri"],n)}const i=s(t,["bytesBase64Encoded"]);if(i!=null){a(e,["videoBytes"],Da(i))}const r=s(t,["mimeType"]);if(r!=null){a(e,["mimeType"],r)}return e}var Uc;(function(t){t["LANGUAGE_UNSPECIFIED"]="LANGUAGE_UNSPECIFIED";t["PYTHON"]="PYTHON"})(Uc||(Uc={}));var Lc;(function(t){t["OUTCOME_UNSPECIFIED"]="OUTCOME_UNSPECIFIED";t["OUTCOME_OK"]="OUTCOME_OK";t["OUTCOME_FAILED"]="OUTCOME_FAILED";t["OUTCOME_DEADLINE_EXCEEDED"]="OUTCOME_DEADLINE_EXCEEDED"})(Lc||(Lc={}));var Gc;(function(t){t["SCHEDULING_UNSPECIFIED"]="SCHEDULING_UNSPECIFIED";t["SILENT"]="SILENT";t["WHEN_IDLE"]="WHEN_IDLE";t["INTERRUPT"]="INTERRUPT"})(Gc||(Gc={}));var gt;(function(t){t["TYPE_UNSPECIFIED"]="TYPE_UNSPECIFIED";t["STRING"]="STRING";t["NUMBER"]="NUMBER";t["INTEGER"]="INTEGER";t["BOOLEAN"]="BOOLEAN";t["ARRAY"]="ARRAY";t["OBJECT"]="OBJECT";t["NULL"]="NULL"})(gt||(gt={}));var Oc;(function(t){t["ENVIRONMENT_UNSPECIFIED"]="ENVIRONMENT_UNSPECIFIED";t["ENVIRONMENT_BROWSER"]="ENVIRONMENT_BROWSER"})(Oc||(Oc={}));var bc;(function(t){t["AUTH_TYPE_UNSPECIFIED"]="AUTH_TYPE_UNSPECIFIED";t["NO_AUTH"]="NO_AUTH";t["API_KEY_AUTH"]="API_KEY_AUTH";t["HTTP_BASIC_AUTH"]="HTTP_BASIC_AUTH";t["GOOGLE_SERVICE_ACCOUNT_AUTH"]="GOOGLE_SERVICE_ACCOUNT_AUTH";t["OAUTH"]="OAUTH";t["OIDC_AUTH"]="OIDC_AUTH"})(bc||(bc={}));var Fc;(function(t){t["HTTP_IN_UNSPECIFIED"]="HTTP_IN_UNSPECIFIED";t["HTTP_IN_QUERY"]="HTTP_IN_QUERY";t["HTTP_IN_HEADER"]="HTTP_IN_HEADER";t["HTTP_IN_PATH"]="HTTP_IN_PATH";t["HTTP_IN_BODY"]="HTTP_IN_BODY";t["HTTP_IN_COOKIE"]="HTTP_IN_COOKIE"})(Fc||(Fc={}));var qc;(function(t){t["API_SPEC_UNSPECIFIED"]="API_SPEC_UNSPECIFIED";t["SIMPLE_SEARCH"]="SIMPLE_SEARCH";t["ELASTIC_SEARCH"]="ELASTIC_SEARCH"})(qc||(qc={}));var Hc;(function(t){t["PHISH_BLOCK_THRESHOLD_UNSPECIFIED"]="PHISH_BLOCK_THRESHOLD_UNSPECIFIED";t["BLOCK_LOW_AND_ABOVE"]="BLOCK_LOW_AND_ABOVE";t["BLOCK_MEDIUM_AND_ABOVE"]="BLOCK_MEDIUM_AND_ABOVE";t["BLOCK_HIGH_AND_ABOVE"]="BLOCK_HIGH_AND_ABOVE";t["BLOCK_HIGHER_AND_ABOVE"]="BLOCK_HIGHER_AND_ABOVE";t["BLOCK_VERY_HIGH_AND_ABOVE"]="BLOCK_VERY_HIGH_AND_ABOVE";t["BLOCK_ONLY_EXTREMELY_HIGH"]="BLOCK_ONLY_EXTREMELY_HIGH"})(Hc||(Hc={}));var Vc;(function(t){t["UNSPECIFIED"]="UNSPECIFIED";t["BLOCKING"]="BLOCKING";t["NON_BLOCKING"]="NON_BLOCKING"})(Vc||(Vc={}));var Bc;(function(t){t["MODE_UNSPECIFIED"]="MODE_UNSPECIFIED";t["MODE_DYNAMIC"]="MODE_DYNAMIC"})(Bc||(Bc={}));var kt;(function(t){t["MODE_UNSPECIFIED"]="MODE_UNSPECIFIED";t["AUTO"]="AUTO";t["ANY"]="ANY";t["NONE"]="NONE";t["VALIDATED"]="VALIDATED"})(kt||(kt={}));var $c;(function(t){t["THINKING_LEVEL_UNSPECIFIED"]="THINKING_LEVEL_UNSPECIFIED";t["MINIMAL"]="MINIMAL";t["LOW"]="LOW";t["MEDIUM"]="MEDIUM";t["HIGH"]="HIGH"})($c||($c={}));var Jc;(function(t){t["DONT_ALLOW"]="DONT_ALLOW";t["ALLOW_ADULT"]="ALLOW_ADULT";t["ALLOW_ALL"]="ALLOW_ALL"})(Jc||(Jc={}));var Kc;(function(t){t["PROMINENT_PEOPLE_UNSPECIFIED"]="PROMINENT_PEOPLE_UNSPECIFIED";t["ALLOW_PROMINENT_PEOPLE"]="ALLOW_PROMINENT_PEOPLE";t["BLOCK_PROMINENT_PEOPLE"]="BLOCK_PROMINENT_PEOPLE"})(Kc||(Kc={}));var Wc;(function(t){t["HARM_CATEGORY_UNSPECIFIED"]="HARM_CATEGORY_UNSPECIFIED";t["HARM_CATEGORY_HARASSMENT"]="HARM_CATEGORY_HARASSMENT";t["HARM_CATEGORY_HATE_SPEECH"]="HARM_CATEGORY_HATE_SPEECH";t["HARM_CATEGORY_SEXUALLY_EXPLICIT"]="HARM_CATEGORY_SEXUALLY_EXPLICIT";t["HARM_CATEGORY_DANGEROUS_CONTENT"]="HARM_CATEGORY_DANGEROUS_CONTENT";t["HARM_CATEGORY_CIVIC_INTEGRITY"]="HARM_CATEGORY_CIVIC_INTEGRITY";t["HARM_CATEGORY_IMAGE_HATE"]="HARM_CATEGORY_IMAGE_HATE";t["HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT"]="HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT";t["HARM_CATEGORY_IMAGE_HARASSMENT"]="HARM_CATEGORY_IMAGE_HARASSMENT";t["HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT"]="HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT";t["HARM_CATEGORY_JAILBREAK"]="HARM_CATEGORY_JAILBREAK"})(Wc||(Wc={}));var Yc;(function(t){t["HARM_BLOCK_METHOD_UNSPECIFIED"]="HARM_BLOCK_METHOD_UNSPECIFIED";t["SEVERITY"]="SEVERITY";t["PROBABILITY"]="PROBABILITY"})(Yc||(Yc={}));var zc;(function(t){t["HARM_BLOCK_THRESHOLD_UNSPECIFIED"]="HARM_BLOCK_THRESHOLD_UNSPECIFIED";t["BLOCK_LOW_AND_ABOVE"]="BLOCK_LOW_AND_ABOVE";t["BLOCK_MEDIUM_AND_ABOVE"]="BLOCK_MEDIUM_AND_ABOVE";t["BLOCK_ONLY_HIGH"]="BLOCK_ONLY_HIGH";t["BLOCK_NONE"]="BLOCK_NONE";t["OFF"]="OFF"})(zc||(zc={}));var fe;(function(t){t["FINISH_REASON_UNSPECIFIED"]="FINISH_REASON_UNSPECIFIED";t["STOP"]="STOP";t["MAX_TOKENS"]="MAX_TOKENS";t["SAFETY"]="SAFETY";t["RECITATION"]="RECITATION";t["LANGUAGE"]="LANGUAGE";t["OTHER"]="OTHER";t["BLOCKLIST"]="BLOCKLIST";t["PROHIBITED_CONTENT"]="PROHIBITED_CONTENT";t["SPII"]="SPII";t["MALFORMED_FUNCTION_CALL"]="MALFORMED_FUNCTION_CALL";t["IMAGE_SAFETY"]="IMAGE_SAFETY";t["UNEXPECTED_TOOL_CALL"]="UNEXPECTED_TOOL_CALL";t["IMAGE_PROHIBITED_CONTENT"]="IMAGE_PROHIBITED_CONTENT";t["NO_IMAGE"]="NO_IMAGE";t["IMAGE_RECITATION"]="IMAGE_RECITATION";t["IMAGE_OTHER"]="IMAGE_OTHER"})(fe||(fe={}));var Xc;(function(t){t["HARM_PROBABILITY_UNSPECIFIED"]="HARM_PROBABILITY_UNSPECIFIED";t["NEGLIGIBLE"]="NEGLIGIBLE";t["LOW"]="LOW";t["MEDIUM"]="MEDIUM";t["HIGH"]="HIGH"})(Xc||(Xc={}));var Qc;(function(t){t["HARM_SEVERITY_UNSPECIFIED"]="HARM_SEVERITY_UNSPECIFIED";t["HARM_SEVERITY_NEGLIGIBLE"]="HARM_SEVERITY_NEGLIGIBLE";t["HARM_SEVERITY_LOW"]="HARM_SEVERITY_LOW";t["HARM_SEVERITY_MEDIUM"]="HARM_SEVERITY_MEDIUM";t["HARM_SEVERITY_HIGH"]="HARM_SEVERITY_HIGH"})(Qc||(Qc={}));var Zc;(function(t){t["URL_RETRIEVAL_STATUS_UNSPECIFIED"]="URL_RETRIEVAL_STATUS_UNSPECIFIED";t["URL_RETRIEVAL_STATUS_SUCCESS"]="URL_RETRIEVAL_STATUS_SUCCESS";t["URL_RETRIEVAL_STATUS_ERROR"]="URL_RETRIEVAL_STATUS_ERROR";t["URL_RETRIEVAL_STATUS_PAYWALL"]="URL_RETRIEVAL_STATUS_PAYWALL";t["URL_RETRIEVAL_STATUS_UNSAFE"]="URL_RETRIEVAL_STATUS_UNSAFE"})(Zc||(Zc={}));var jc;(function(t){t["BLOCKED_REASON_UNSPECIFIED"]="BLOCKED_REASON_UNSPECIFIED";t["SAFETY"]="SAFETY";t["OTHER"]="OTHER";t["BLOCKLIST"]="BLOCKLIST";t["PROHIBITED_CONTENT"]="PROHIBITED_CONTENT";t["IMAGE_SAFETY"]="IMAGE_SAFETY";t["MODEL_ARMOR"]="MODEL_ARMOR";t["JAILBREAK"]="JAILBREAK"})(jc||(jc={}));var ed;(function(t){t["TRAFFIC_TYPE_UNSPECIFIED"]="TRAFFIC_TYPE_UNSPECIFIED";t["ON_DEMAND"]="ON_DEMAND";t["ON_DEMAND_PRIORITY"]="ON_DEMAND_PRIORITY";t["ON_DEMAND_FLEX"]="ON_DEMAND_FLEX";t["PROVISIONED_THROUGHPUT"]="PROVISIONED_THROUGHPUT"})(ed||(ed={}));var bi;(function(t){t["MODALITY_UNSPECIFIED"]="MODALITY_UNSPECIFIED";t["TEXT"]="TEXT";t["IMAGE"]="IMAGE";t["AUDIO"]="AUDIO";t["VIDEO"]="VIDEO"})(bi||(bi={}));var td;(function(t){t["MODEL_STAGE_UNSPECIFIED"]="MODEL_STAGE_UNSPECIFIED";t["UNSTABLE_EXPERIMENTAL"]="UNSTABLE_EXPERIMENTAL";t["EXPERIMENTAL"]="EXPERIMENTAL";t["PREVIEW"]="PREVIEW";t["STABLE"]="STABLE";t["LEGACY"]="LEGACY";t["DEPRECATED"]="DEPRECATED";t["RETIRED"]="RETIRED"})(td||(td={}));var nd;(function(t){t["MEDIA_RESOLUTION_UNSPECIFIED"]="MEDIA_RESOLUTION_UNSPECIFIED";t["MEDIA_RESOLUTION_LOW"]="MEDIA_RESOLUTION_LOW";t["MEDIA_RESOLUTION_MEDIUM"]="MEDIA_RESOLUTION_MEDIUM";t["MEDIA_RESOLUTION_HIGH"]="MEDIA_RESOLUTION_HIGH"})(nd||(nd={}));var id;(function(t){t["TUNING_MODE_UNSPECIFIED"]="TUNING_MODE_UNSPECIFIED";t["TUNING_MODE_FULL"]="TUNING_MODE_FULL";t["TUNING_MODE_PEFT_ADAPTER"]="TUNING_MODE_PEFT_ADAPTER"})(id||(id={}));var rd;(function(t){t["ADAPTER_SIZE_UNSPECIFIED"]="ADAPTER_SIZE_UNSPECIFIED";t["ADAPTER_SIZE_ONE"]="ADAPTER_SIZE_ONE";t["ADAPTER_SIZE_TWO"]="ADAPTER_SIZE_TWO";t["ADAPTER_SIZE_FOUR"]="ADAPTER_SIZE_FOUR";t["ADAPTER_SIZE_EIGHT"]="ADAPTER_SIZE_EIGHT";t["ADAPTER_SIZE_SIXTEEN"]="ADAPTER_SIZE_SIXTEEN";t["ADAPTER_SIZE_THIRTY_TWO"]="ADAPTER_SIZE_THIRTY_TWO"})(rd||(rd={}));var Ds;(function(t){t["JOB_STATE_UNSPECIFIED"]="JOB_STATE_UNSPECIFIED";t["JOB_STATE_QUEUED"]="JOB_STATE_QUEUED";t["JOB_STATE_PENDING"]="JOB_STATE_PENDING";t["JOB_STATE_RUNNING"]="JOB_STATE_RUNNING";t["JOB_STATE_SUCCEEDED"]="JOB_STATE_SUCCEEDED";t["JOB_STATE_FAILED"]="JOB_STATE_FAILED";t["JOB_STATE_CANCELLING"]="JOB_STATE_CANCELLING";t["JOB_STATE_CANCELLED"]="JOB_STATE_CANCELLED";t["JOB_STATE_PAUSED"]="JOB_STATE_PAUSED";t["JOB_STATE_EXPIRED"]="JOB_STATE_EXPIRED";t["JOB_STATE_UPDATING"]="JOB_STATE_UPDATING";t["JOB_STATE_PARTIALLY_SUCCEEDED"]="JOB_STATE_PARTIALLY_SUCCEEDED"})(Ds||(Ds={}));var od;(function(t){t["TUNING_JOB_STATE_UNSPECIFIED"]="TUNING_JOB_STATE_UNSPECIFIED";t["TUNING_JOB_STATE_WAITING_FOR_QUOTA"]="TUNING_JOB_STATE_WAITING_FOR_QUOTA";t["TUNING_JOB_STATE_PROCESSING_DATASET"]="TUNING_JOB_STATE_PROCESSING_DATASET";t["TUNING_JOB_STATE_WAITING_FOR_CAPACITY"]="TUNING_JOB_STATE_WAITING_FOR_CAPACITY";t["TUNING_JOB_STATE_TUNING"]="TUNING_JOB_STATE_TUNING";t["TUNING_JOB_STATE_POST_PROCESSING"]="TUNING_JOB_STATE_POST_PROCESSING"})(od||(od={}));var sd;(function(t){t["AGGREGATION_METRIC_UNSPECIFIED"]="AGGREGATION_METRIC_UNSPECIFIED";t["AVERAGE"]="AVERAGE";t["MODE"]="MODE";t["STANDARD_DEVIATION"]="STANDARD_DEVIATION";t["VARIANCE"]="VARIANCE";t["MINIMUM"]="MINIMUM";t["MAXIMUM"]="MAXIMUM";t["MEDIAN"]="MEDIAN";t["PERCENTILE_P90"]="PERCENTILE_P90";t["PERCENTILE_P95"]="PERCENTILE_P95";t["PERCENTILE_P99"]="PERCENTILE_P99"})(sd||(sd={}));var ad;(function(t){t["PAIRWISE_CHOICE_UNSPECIFIED"]="PAIRWISE_CHOICE_UNSPECIFIED";t["BASELINE"]="BASELINE";t["CANDIDATE"]="CANDIDATE";t["TIE"]="TIE"})(ad||(ad={}));var ld;(function(t){t["TUNING_TASK_UNSPECIFIED"]="TUNING_TASK_UNSPECIFIED";t["TUNING_TASK_I2V"]="TUNING_TASK_I2V";t["TUNING_TASK_T2V"]="TUNING_TASK_T2V";t["TUNING_TASK_R2V"]="TUNING_TASK_R2V"})(ld||(ld={}));var ud;(function(t){t["STATE_UNSPECIFIED"]="STATE_UNSPECIFIED";t["STATE_PENDING"]="STATE_PENDING";t["STATE_ACTIVE"]="STATE_ACTIVE";t["STATE_FAILED"]="STATE_FAILED"})(ud||(ud={}));var cd;(function(t){t["MEDIA_RESOLUTION_UNSPECIFIED"]="MEDIA_RESOLUTION_UNSPECIFIED";t["MEDIA_RESOLUTION_LOW"]="MEDIA_RESOLUTION_LOW";t["MEDIA_RESOLUTION_MEDIUM"]="MEDIA_RESOLUTION_MEDIUM";t["MEDIA_RESOLUTION_HIGH"]="MEDIA_RESOLUTION_HIGH";t["MEDIA_RESOLUTION_ULTRA_HIGH"]="MEDIA_RESOLUTION_ULTRA_HIGH"})(cd||(cd={}));var dd;(function(t){t["TOOL_TYPE_UNSPECIFIED"]="TOOL_TYPE_UNSPECIFIED";t["GOOGLE_SEARCH_WEB"]="GOOGLE_SEARCH_WEB";t["GOOGLE_SEARCH_IMAGE"]="GOOGLE_SEARCH_IMAGE";t["URL_CONTEXT"]="URL_CONTEXT";t["GOOGLE_MAPS"]="GOOGLE_MAPS";t["FILE_SEARCH"]="FILE_SEARCH"})(dd||(dd={}));var Us;(function(t){t["COLLECTION"]="COLLECTION"})(Us||(Us={}));var fd;(function(t){t["UNSPECIFIED"]="unspecified";t["FLEX"]="flex";t["STANDARD"]="standard";t["PRIORITY"]="priority"})(fd||(fd={}));var pd;(function(t){t["FEATURE_SELECTION_PREFERENCE_UNSPECIFIED"]="FEATURE_SELECTION_PREFERENCE_UNSPECIFIED";t["PRIORITIZE_QUALITY"]="PRIORITIZE_QUALITY";t["BALANCED"]="BALANCED";t["PRIORITIZE_COST"]="PRIORITIZE_COST"})(pd||(pd={}));var Fi;(function(t){t["PREDICT"]="PREDICT";t["EMBED_CONTENT"]="EMBED_CONTENT"})(Fi||(Fi={}));var hd;(function(t){t["BLOCK_LOW_AND_ABOVE"]="BLOCK_LOW_AND_ABOVE";t["BLOCK_MEDIUM_AND_ABOVE"]="BLOCK_MEDIUM_AND_ABOVE";t["BLOCK_ONLY_HIGH"]="BLOCK_ONLY_HIGH";t["BLOCK_NONE"]="BLOCK_NONE"})(hd||(hd={}));var gd;(function(t){t["auto"]="auto";t["en"]="en";t["ja"]="ja";t["ko"]="ko";t["hi"]="hi";t["zh"]="zh";t["pt"]="pt";t["es"]="es"})(gd||(gd={}));var md;(function(t){t["MASK_MODE_DEFAULT"]="MASK_MODE_DEFAULT";t["MASK_MODE_USER_PROVIDED"]="MASK_MODE_USER_PROVIDED";t["MASK_MODE_BACKGROUND"]="MASK_MODE_BACKGROUND";t["MASK_MODE_FOREGROUND"]="MASK_MODE_FOREGROUND";t["MASK_MODE_SEMANTIC"]="MASK_MODE_SEMANTIC"})(md||(md={}));var yd;(function(t){t["CONTROL_TYPE_DEFAULT"]="CONTROL_TYPE_DEFAULT";t["CONTROL_TYPE_CANNY"]="CONTROL_TYPE_CANNY";t["CONTROL_TYPE_SCRIBBLE"]="CONTROL_TYPE_SCRIBBLE";t["CONTROL_TYPE_FACE_MESH"]="CONTROL_TYPE_FACE_MESH"})(yd||(yd={}));var Ed;(function(t){t["SUBJECT_TYPE_DEFAULT"]="SUBJECT_TYPE_DEFAULT";t["SUBJECT_TYPE_PERSON"]="SUBJECT_TYPE_PERSON";t["SUBJECT_TYPE_ANIMAL"]="SUBJECT_TYPE_ANIMAL";t["SUBJECT_TYPE_PRODUCT"]="SUBJECT_TYPE_PRODUCT"})(Ed||(Ed={}));var _d;(function(t){t["EDIT_MODE_DEFAULT"]="EDIT_MODE_DEFAULT";t["EDIT_MODE_INPAINT_REMOVAL"]="EDIT_MODE_INPAINT_REMOVAL";t["EDIT_MODE_INPAINT_INSERTION"]="EDIT_MODE_INPAINT_INSERTION";t["EDIT_MODE_OUTPAINT"]="EDIT_MODE_OUTPAINT";t["EDIT_MODE_CONTROLLED_EDITING"]="EDIT_MODE_CONTROLLED_EDITING";t["EDIT_MODE_STYLE"]="EDIT_MODE_STYLE";t["EDIT_MODE_BGSWAP"]="EDIT_MODE_BGSWAP";t["EDIT_MODE_PRODUCT_IMAGE"]="EDIT_MODE_PRODUCT_IMAGE"})(_d||(_d={}));var Td;(function(t){t["FOREGROUND"]="FOREGROUND";t["BACKGROUND"]="BACKGROUND";t["PROMPT"]="PROMPT";t["SEMANTIC"]="SEMANTIC";t["INTERACTIVE"]="INTERACTIVE"})(Td||(Td={}));var Ad;(function(t){t["ASSET"]="ASSET";t["STYLE"]="STYLE"})(Ad||(Ad={}));var Cd;(function(t){t["INSERT"]="INSERT";t["REMOVE"]="REMOVE";t["REMOVE_STATIC"]="REMOVE_STATIC";t["OUTPAINT"]="OUTPAINT"})(Cd||(Cd={}));var vd;(function(t){t["OPTIMIZED"]="OPTIMIZED";t["LOSSLESS"]="LOSSLESS"})(vd||(vd={}));var Sd;(function(t){t["CROP"]="CROP";t["PAD"]="PAD"})(Sd||(Sd={}));var Id;(function(t){t["SUPERVISED_FINE_TUNING"]="SUPERVISED_FINE_TUNING";t["PREFERENCE_TUNING"]="PREFERENCE_TUNING";t["DISTILLATION"]="DISTILLATION"})(Id||(Id={}));var wd;(function(t){t["STATE_UNSPECIFIED"]="STATE_UNSPECIFIED";t["PROCESSING"]="PROCESSING";t["ACTIVE"]="ACTIVE";t["FAILED"]="FAILED"})(wd||(wd={}));var Rd;(function(t){t["SOURCE_UNSPECIFIED"]="SOURCE_UNSPECIFIED";t["UPLOADED"]="UPLOADED";t["GENERATED"]="GENERATED";t["REGISTERED"]="REGISTERED"})(Rd||(Rd={}));var Pd;(function(t){t["TURN_COMPLETE_REASON_UNSPECIFIED"]="TURN_COMPLETE_REASON_UNSPECIFIED";t["MALFORMED_FUNCTION_CALL"]="MALFORMED_FUNCTION_CALL";t["RESPONSE_REJECTED"]="RESPONSE_REJECTED";t["NEED_MORE_INPUT"]="NEED_MORE_INPUT";t["PROHIBITED_INPUT_CONTENT"]="PROHIBITED_INPUT_CONTENT";t["IMAGE_PROHIBITED_INPUT_CONTENT"]="IMAGE_PROHIBITED_INPUT_CONTENT";t["INPUT_TEXT_CONTAIN_PROMINENT_PERSON_PROHIBITED"]="INPUT_TEXT_CONTAIN_PROMINENT_PERSON_PROHIBITED";t["INPUT_IMAGE_CELEBRITY"]="INPUT_IMAGE_CELEBRITY";t["INPUT_IMAGE_PHOTO_REALISTIC_CHILD_PROHIBITED"]="INPUT_IMAGE_PHOTO_REALISTIC_CHILD_PROHIBITED";t["INPUT_TEXT_NCII_PROHIBITED"]="INPUT_TEXT_NCII_PROHIBITED";t["INPUT_OTHER"]="INPUT_OTHER";t["INPUT_IP_PROHIBITED"]="INPUT_IP_PROHIBITED";t["BLOCKLIST"]="BLOCKLIST";t["UNSAFE_PROMPT_FOR_IMAGE_GENERATION"]="UNSAFE_PROMPT_FOR_IMAGE_GENERATION";t["GENERATED_IMAGE_SAFETY"]="GENERATED_IMAGE_SAFETY";t["GENERATED_CONTENT_SAFETY"]="GENERATED_CONTENT_SAFETY";t["GENERATED_AUDIO_SAFETY"]="GENERATED_AUDIO_SAFETY";t["GENERATED_VIDEO_SAFETY"]="GENERATED_VIDEO_SAFETY";t["GENERATED_CONTENT_PROHIBITED"]="GENERATED_CONTENT_PROHIBITED";t["GENERATED_CONTENT_BLOCKLIST"]="GENERATED_CONTENT_BLOCKLIST";t["GENERATED_IMAGE_PROHIBITED"]="GENERATED_IMAGE_PROHIBITED";t["GENERATED_IMAGE_CELEBRITY"]="GENERATED_IMAGE_CELEBRITY";t["GENERATED_IMAGE_PROMINENT_PEOPLE_DETECTED_BY_REWRITER"]="GENERATED_IMAGE_PROMINENT_PEOPLE_DETECTED_BY_REWRITER";t["GENERATED_IMAGE_IDENTIFIABLE_PEOPLE"]="GENERATED_IMAGE_IDENTIFIABLE_PEOPLE";t["GENERATED_IMAGE_MINORS"]="GENERATED_IMAGE_MINORS";t["OUTPUT_IMAGE_IP_PROHIBITED"]="OUTPUT_IMAGE_IP_PROHIBITED";t["GENERATED_OTHER"]="GENERATED_OTHER";t["MAX_REGENERATION_REACHED"]="MAX_REGENERATION_REACHED"})(Pd||(Pd={}));var Nd;(function(t){t["MODALITY_UNSPECIFIED"]="MODALITY_UNSPECIFIED";t["TEXT"]="TEXT";t["IMAGE"]="IMAGE";t["VIDEO"]="VIDEO";t["AUDIO"]="AUDIO";t["DOCUMENT"]="DOCUMENT"})(Nd||(Nd={}));var Md;(function(t){t["VAD_SIGNAL_TYPE_UNSPECIFIED"]="VAD_SIGNAL_TYPE_UNSPECIFIED";t["VAD_SIGNAL_TYPE_SOS"]="VAD_SIGNAL_TYPE_SOS";t["VAD_SIGNAL_TYPE_EOS"]="VAD_SIGNAL_TYPE_EOS"})(Md||(Md={}));var kd;(function(t){t["TYPE_UNSPECIFIED"]="TYPE_UNSPECIFIED";t["ACTIVITY_START"]="ACTIVITY_START";t["ACTIVITY_END"]="ACTIVITY_END"})(kd||(kd={}));var xd;(function(t){t["START_SENSITIVITY_UNSPECIFIED"]="START_SENSITIVITY_UNSPECIFIED";t["START_SENSITIVITY_HIGH"]="START_SENSITIVITY_HIGH";t["START_SENSITIVITY_LOW"]="START_SENSITIVITY_LOW"})(xd||(xd={}));var Dd;(function(t){t["END_SENSITIVITY_UNSPECIFIED"]="END_SENSITIVITY_UNSPECIFIED";t["END_SENSITIVITY_HIGH"]="END_SENSITIVITY_HIGH";t["END_SENSITIVITY_LOW"]="END_SENSITIVITY_LOW"})(Dd||(Dd={}));var Ud;(function(t){t["ACTIVITY_HANDLING_UNSPECIFIED"]="ACTIVITY_HANDLING_UNSPECIFIED";t["START_OF_ACTIVITY_INTERRUPTS"]="START_OF_ACTIVITY_INTERRUPTS";t["NO_INTERRUPTION"]="NO_INTERRUPTION"})(Ud||(Ud={}));var Ld;(function(t){t["TURN_COVERAGE_UNSPECIFIED"]="TURN_COVERAGE_UNSPECIFIED";t["TURN_INCLUDES_ONLY_ACTIVITY"]="TURN_INCLUDES_ONLY_ACTIVITY";t["TURN_INCLUDES_ALL_INPUT"]="TURN_INCLUDES_ALL_INPUT";t["TURN_INCLUDES_AUDIO_ACTIVITY_AND_ALL_VIDEO"]="TURN_INCLUDES_AUDIO_ACTIVITY_AND_ALL_VIDEO"})(Ld||(Ld={}));var Gd;(function(t){t["SCALE_UNSPECIFIED"]="SCALE_UNSPECIFIED";t["C_MAJOR_A_MINOR"]="C_MAJOR_A_MINOR";t["D_FLAT_MAJOR_B_FLAT_MINOR"]="D_FLAT_MAJOR_B_FLAT_MINOR";t["D_MAJOR_B_MINOR"]="D_MAJOR_B_MINOR";t["E_FLAT_MAJOR_C_MINOR"]="E_FLAT_MAJOR_C_MINOR";t["E_MAJOR_D_FLAT_MINOR"]="E_MAJOR_D_FLAT_MINOR";t["F_MAJOR_D_MINOR"]="F_MAJOR_D_MINOR";t["G_FLAT_MAJOR_E_FLAT_MINOR"]="G_FLAT_MAJOR_E_FLAT_MINOR";t["G_MAJOR_E_MINOR"]="G_MAJOR_E_MINOR";t["A_FLAT_MAJOR_F_MINOR"]="A_FLAT_MAJOR_F_MINOR";t["A_MAJOR_G_FLAT_MINOR"]="A_MAJOR_G_FLAT_MINOR";t["B_FLAT_MAJOR_G_MINOR"]="B_FLAT_MAJOR_G_MINOR";t["B_MAJOR_A_FLAT_MINOR"]="B_MAJOR_A_FLAT_MINOR"})(Gd||(Gd={}));var Od;(function(t){t["MUSIC_GENERATION_MODE_UNSPECIFIED"]="MUSIC_GENERATION_MODE_UNSPECIFIED";t["QUALITY"]="QUALITY";t["DIVERSITY"]="DIVERSITY";t["VOCALIZATION"]="VOCALIZATION"})(Od||(Od={}));var Xt;(function(t){t["PLAYBACK_CONTROL_UNSPECIFIED"]="PLAYBACK_CONTROL_UNSPECIFIED";t["PLAY"]="PLAY";t["PAUSE"]="PAUSE";t["STOP"]="STOP";t["RESET_CONTEXT"]="RESET_CONTEXT"})(Xt||(Xt={}));var _t=class{constructor(e){const n={};for(const i of e.headers.entries()){n[i[0]]=i[1]}this.headers=n;this.responseInternal=e}json(){return this.responseInternal.json()}};var Mt=class{get text(){var e,n,i,r,o,l,u,c;if(((r=(i=(n=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||n===void 0?void 0:n.content)===null||i===void 0?void 0:i.parts)===null||r===void 0?void 0:r.length)===0){return void 0}if(this.candidates&&this.candidates.length>1){console.warn("there are multiple candidates in the response, returning text from the first one.")}let d="";let f=false;const p=[];for(const h of(c=(u=(l=(o=this.candidates)===null||o===void 0?void 0:o[0])===null||l===void 0?void 0:l.content)===null||u===void 0?void 0:u.parts)!==null&&c!==void 0?c:[]){for(const[m,_]of Object.entries(h)){if(m!=="text"&&m!=="thought"&&m!=="thoughtSignature"&&(_!==null||_!==void 0)){p.push(m)}}if(typeof h.text==="string"){if(typeof h.thought==="boolean"&&h.thought){continue}f=true;d+=h.text}}if(p.length>0){console.warn(`there are non-text parts ${p} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`)}return f?d:void 0}get data(){var e,n,i,r,o,l,u,c;if(((r=(i=(n=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||n===void 0?void 0:n.content)===null||i===void 0?void 0:i.parts)===null||r===void 0?void 0:r.length)===0){return void 0}if(this.candidates&&this.candidates.length>1){console.warn("there are multiple candidates in the response, returning data from the first one.")}let d="";const f=[];for(const p of(c=(u=(l=(o=this.candidates)===null||o===void 0?void 0:o[0])===null||l===void 0?void 0:l.content)===null||u===void 0?void 0:u.parts)!==null&&c!==void 0?c:[]){for(const[h,m]of Object.entries(p)){if(h!=="inlineData"&&(m!==null||m!==void 0)){f.push(h)}}if(p.inlineData&&typeof p.inlineData.data==="string"){d+=atob(p.inlineData.data)}}if(f.length>0){console.warn(`there are non-data parts ${f} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`)}return d.length>0?btoa(d):void 0}get functionCalls(){var e,n,i,r,o,l,u,c;if(((r=(i=(n=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||n===void 0?void 0:n.content)===null||i===void 0?void 0:i.parts)===null||r===void 0?void 0:r.length)===0){return void 0}if(this.candidates&&this.candidates.length>1){console.warn("there are multiple candidates in the response, returning function calls from the first one.")}const d=(c=(u=(l=(o=this.candidates)===null||o===void 0?void 0:o[0])===null||l===void 0?void 0:l.content)===null||u===void 0?void 0:u.parts)===null||c===void 0?void 0:c.filter(f=>f.functionCall).map(f=>f.functionCall).filter(f=>f!==void 0);if((d===null||d===void 0?void 0:d.length)===0){return void 0}return d}get executableCode(){var e,n,i,r,o,l,u,c,d;if(((r=(i=(n=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||n===void 0?void 0:n.content)===null||i===void 0?void 0:i.parts)===null||r===void 0?void 0:r.length)===0){return void 0}if(this.candidates&&this.candidates.length>1){console.warn("there are multiple candidates in the response, returning executable code from the first one.")}const f=(c=(u=(l=(o=this.candidates)===null||o===void 0?void 0:o[0])===null||l===void 0?void 0:l.content)===null||u===void 0?void 0:u.parts)===null||c===void 0?void 0:c.filter(p=>p.executableCode).map(p=>p.executableCode).filter(p=>p!==void 0);if((f===null||f===void 0?void 0:f.length)===0){return void 0}return(d=f===null||f===void 0?void 0:f[0])===null||d===void 0?void 0:d.code}get codeExecutionResult(){var e,n,i,r,o,l,u,c,d;if(((r=(i=(n=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||n===void 0?void 0:n.content)===null||i===void 0?void 0:i.parts)===null||r===void 0?void 0:r.length)===0){return void 0}if(this.candidates&&this.candidates.length>1){console.warn("there are multiple candidates in the response, returning code execution result from the first one.")}const f=(c=(u=(l=(o=this.candidates)===null||o===void 0?void 0:o[0])===null||l===void 0?void 0:l.content)===null||u===void 0?void 0:u.parts)===null||c===void 0?void 0:c.filter(p=>p.codeExecutionResult).map(p=>p.codeExecutionResult).filter(p=>p!==void 0);if((f===null||f===void 0?void 0:f.length)===0){return void 0}return(d=f===null||f===void 0?void 0:f[0])===null||d===void 0?void 0:d.output}};var qi=class{};var Hi=class{};var Ls=class{};var Gs=class{};var Os=class{};var bs=class{};var Vi=class{};var Bi=class{};var $i=class{};var Fs=class{};var Ji=class t{_fromAPIResponse({apiResponse:e,_isVertexAI:n}){const i=new t;let r;const o=e;if(n){r=Fy(o)}else{r=by(o)}Object.assign(i,r);return i}};var qs=class{};var Ki=class{};var Wi=class{};var Yi=class{};var Hs=class{};var Vs=class{};var Bs=class{};var $s=class t{_fromAPIResponse({apiResponse:e,_isVertexAI:n}){const i=new t;const r=e;const o=Ky(r);Object.assign(i,o);return i}};var Js=class{};var Ks=class{};var Ws=class{};var Ys=class{};var zi=class{};var zs=class{get text(){var e,n,i;let r="";let o=false;const l=[];for(const u of(i=(n=(e=this.serverContent)===null||e===void 0?void 0:e.modelTurn)===null||n===void 0?void 0:n.parts)!==null&&i!==void 0?i:[]){for(const[c,d]of Object.entries(u)){if(c!=="text"&&c!=="thought"&&d!==null){l.push(c)}}if(typeof u.text==="string"){if(typeof u.thought==="boolean"&&u.thought){continue}o=true;r+=u.text}}if(l.length>0){console.warn(`there are non-text parts ${l} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`)}return o?r:void 0}get data(){var e,n,i;let r="";const o=[];for(const l of(i=(n=(e=this.serverContent)===null||e===void 0?void 0:e.modelTurn)===null||n===void 0?void 0:n.parts)!==null&&i!==void 0?i:[]){for(const[u,c]of Object.entries(l)){if(u!=="inlineData"&&c!==null){o.push(u)}}if(l.inlineData&&typeof l.inlineData.data==="string"){r+=atob(l.inlineData.data)}}if(o.length>0){console.warn(`there are non-data parts ${o} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`)}return r.length>0?btoa(r):void 0}};var Xs=class{get audioChunk(){if(this.serverContent&&this.serverContent.audioChunks&&this.serverContent.audioChunks.length>0){return this.serverContent.audioChunks[0]}return void 0}};var Xi=class t{_fromAPIResponse({apiResponse:e,_isVertexAI:n}){const i=new t;const r=e;const o=Ua(r);Object.assign(i,o);return i}};function j(t,e){if(!e||typeof e!=="string"){throw new Error("model is required and must be a string")}if(e.includes("..")||e.includes("?")||e.includes("&")){throw new Error("invalid model parameter")}if(t.isVertexAI()){if(e.startsWith("publishers/")||e.startsWith("projects/")||e.startsWith("models/")){return e}else if(e.indexOf("/")>=0){const n=e.split("/",2);return`publishers/${n[0]}/models/${n[1]}`}else{return`publishers/google/models/${e}`}}else{if(e.startsWith("models/")||e.startsWith("tunedModels/")){return e}else{return`models/${e}`}}}function gf(t,e){const n=j(t,e);if(!n){return""}if(n.startsWith("publishers/")&&t.isVertexAI()){return`projects/${t.getProject()}/locations/${t.getLocation()}/${n}`}else if(n.startsWith("models/")&&t.isVertexAI()){return`projects/${t.getProject()}/locations/${t.getLocation()}/publishers/google/${n}`}else{return n}}function mf(t){if(Array.isArray(t)){return t.map(e=>Qi(e))}else{return[Qi(t)]}}function Qi(t){if(typeof t==="object"&&t!==null){return t}throw new Error(`Could not parse input as Blob. Unsupported blob type: ${typeof t}`)}function yf(t){const e=Qi(t);if(e.mimeType&&e.mimeType.startsWith("image/")){return e}throw new Error(`Unsupported mime type: ${e.mimeType}`)}function Ef(t){const e=Qi(t);if(e.mimeType&&e.mimeType.startsWith("audio/")){return e}throw new Error(`Unsupported mime type: ${e.mimeType}`)}function bd(t){if(t===null||t===void 0){throw new Error("PartUnion is required")}if(typeof t==="object"){return t}if(typeof t==="string"){return{text:t}}throw new Error(`Unsupported part type: ${typeof t}`)}function _f(t){if(t===null||t===void 0||Array.isArray(t)&&t.length===0){throw new Error("PartListUnion is required")}if(Array.isArray(t)){return t.map(e=>bd(e))}return[bd(t)]}function Qs(t){return t!==null&&t!==void 0&&typeof t==="object"&&"parts"in t&&Array.isArray(t.parts)}function Fd(t){return t!==null&&t!==void 0&&typeof t==="object"&&"functionCall"in t}function qd(t){return t!==null&&t!==void 0&&typeof t==="object"&&"functionResponse"in t}function he(t){if(t===null||t===void 0){throw new Error("ContentUnion is required")}if(Qs(t)){return t}return{role:"user",parts:_f(t)}}function La(t,e){if(!e){return[]}if(t.isVertexAI()&&Array.isArray(e)){return e.flatMap(n=>{const i=he(n);if(i.parts&&i.parts.length>0&&i.parts[0].text!==void 0){return[i.parts[0].text]}return[]})}else if(t.isVertexAI()){const n=he(e);if(n.parts&&n.parts.length>0&&n.parts[0].text!==void 0){return[n.parts[0].text]}return[]}if(Array.isArray(e)){return e.map(n=>he(n))}return[he(e)]}function Ae(t){if(t===null||t===void 0||Array.isArray(t)&&t.length===0){throw new Error("contents are required")}if(!Array.isArray(t)){if(Fd(t)||qd(t)){throw new Error("To specify functionCall or functionResponse parts, please wrap them in a Content object, specifying the role for them")}return[he(t)]}const e=[];const n=[];const i=Qs(t[0]);for(const r of t){const o=Qs(r);if(o!=i){throw new Error("Mixing Content and Parts is not supported, please group the parts into a the appropriate Content objects and specify the roles for them")}if(o){e.push(r)}else if(Fd(r)||qd(r)){throw new Error("To specify functionCall or functionResponse parts, please wrap them, and any other parts, in Content objects as appropriate, specifying the role for them")}else{n.push(r)}}if(!i){e.push({role:"user",parts:_f(n)})}return e}function Qy(t,e){if(t.includes("null")){e["nullable"]=true}const n=t.filter(i=>i!=="null");if(n.length===1){e["type"]=Object.values(gt).includes(n[0].toUpperCase())?n[0].toUpperCase():gt.TYPE_UNSPECIFIED}else{e["anyOf"]=[];for(const i of n){e["anyOf"].push({"type":Object.values(gt).includes(i.toUpperCase())?i.toUpperCase():gt.TYPE_UNSPECIFIED})}}}function Qt(t){const e={};const n=["items"];const i=["anyOf"];const r=["properties"];if(t["type"]&&t["anyOf"]){throw new Error("type and anyOf cannot be both populated.")}const o=t["anyOf"];if(o!=null&&o.length==2){if(o[0]["type"]==="null"){e["nullable"]=true;t=o[1]}else if(o[1]["type"]==="null"){e["nullable"]=true;t=o[0]}}if(t["type"]instanceof Array){Qy(t["type"],e)}for(const[l,u]of Object.entries(t)){if(u==null){continue}if(l=="type"){if(u==="null"){throw new Error("type: null can not be the only possible type for the field.")}if(u instanceof Array){continue}e["type"]=Object.values(gt).includes(u.toUpperCase())?u.toUpperCase():gt.TYPE_UNSPECIFIED}else if(n.includes(l)){e[l]=Qt(u)}else if(i.includes(l)){const c=[];for(const d of u){if(d["type"]=="null"){e["nullable"]=true;continue}c.push(Qt(d))}e[l]=c}else if(r.includes(l)){const c={};for(const[d,f]of Object.entries(u)){c[d]=Qt(f)}e[l]=c}else{if(l==="additionalProperties"){continue}e[l]=u}}return e}function Ga(t){return Qt(t)}function Oa(t){if(typeof t==="object"){return t}else if(typeof t==="string"){return{voiceConfig:{prebuiltVoiceConfig:{voiceName:t}}}}else{throw new Error(`Unsupported speechConfig type: ${typeof t}`)}}function ba(t){if("multiSpeakerVoiceConfig"in t){throw new Error("multiSpeakerVoiceConfig is not supported in the live API.")}return t}function tn(t){if(t.functionDeclarations){for(const e of t.functionDeclarations){if(e.parameters){if(!Object.keys(e.parameters).includes("$schema")){e.parameters=Qt(e.parameters)}else{if(!e.parametersJsonSchema){e.parametersJsonSchema=e.parameters;delete e.parameters}}}if(e.response){if(!Object.keys(e.response).includes("$schema")){e.response=Qt(e.response)}else{if(!e.responseJsonSchema){e.responseJsonSchema=e.response;delete e.response}}}}}return t}function nn(t){if(t===void 0||t===null){throw new Error("tools is required")}if(!Array.isArray(t)){throw new Error("tools is required and must be an array of Tools")}const e=[];for(const n of t){e.push(n)}return e}function Zy(t,e,n,i=1){const r=!e.startsWith(`${n}/`)&&e.split("/").length===i;if(t.isVertexAI()){if(e.startsWith("projects/")){return e}else if(e.startsWith("locations/")){return`projects/${t.getProject()}/${e}`}else if(e.startsWith(`${n}/`)){return`projects/${t.getProject()}/locations/${t.getLocation()}/${e}`}else if(r){return`projects/${t.getProject()}/locations/${t.getLocation()}/${n}/${e}`}else{return e}}if(r){return`${n}/${e}`}return e}function lt(t,e){if(typeof e!=="string"){throw new Error("name must be a string")}return Zy(t,e,"cachedContents")}function Tf(t){switch(t){case"STATE_UNSPECIFIED":return"JOB_STATE_UNSPECIFIED";case"CREATING":return"JOB_STATE_RUNNING";case"ACTIVE":return"JOB_STATE_SUCCEEDED";case"FAILED":return"JOB_STATE_FAILED";default:return t}}function Tt(t){return Da(t)}function jy(t){return t!==null&&t!==void 0&&typeof t==="object"&&"name"in t}function Af(t){return t!==null&&t!==void 0&&typeof t==="object"&&"video"in t}function Cf(t){return t!==null&&t!==void 0&&typeof t==="object"&&"uri"in t}function Fa(t){var e;let n;if(jy(t)){n=t.name}if(Cf(t)){n=t.uri;if(n===void 0){return void 0}}if(Af(t)){n=(e=t.video)===null||e===void 0?void 0:e.uri;if(n===void 0){return void 0}}if(typeof t==="string"){n=t}if(n===void 0){throw new Error("Could not extract file name from the provided input.")}if(n.startsWith("https://")){const i=n.split("files/")[1];const r=i.match(/[a-z0-9]+/);if(r===null){throw new Error(`Could not extract file name from URI ${n}`)}n=r[0]}else if(n.startsWith("files/")){n=n.split("files/")[1]}return n}function vf(t,e){let n;if(t.isVertexAI()){n=e?"publishers/google/models":"models"}else{n=e?"models":"tunedModels"}return n}function Sf(t){for(const e of["models","tunedModels","publisherModels"]){if(eE(t,e)){return t[e]}}return[]}function eE(t,e){return t!==null&&typeof t==="object"&&e in t}function tE(t,e={}){const n=t;const i={name:n["name"],description:n["description"],parametersJsonSchema:n["inputSchema"]};if(n["outputSchema"]){i["responseJsonSchema"]=n["outputSchema"]}if(e.behavior){i["behavior"]=e.behavior}const r={functionDeclarations:[i]};return r}function nE(t,e={}){const n=[];const i=new Set;for(const r of t){const o=r.name;if(i.has(o)){throw new Error(`Duplicate function name ${o} found in MCP tools. Please ensure function names are unique.`)}i.add(o);const l=tE(r,e);if(l.functionDeclarations){n.push(...l.functionDeclarations)}}return{functionDeclarations:n}}function If(t,e){let n;if(typeof e==="string"){if(t.isVertexAI()){if(e.startsWith("gs://")){n={format:"jsonl",gcsUri:[e]}}else if(e.startsWith("bq://")){n={format:"bigquery",bigqueryUri:e}}else if(/^projects\/[^/]+\/locations\/[^/]+\/datasets\/[^/]+$/.test(e)){n={format:"vertex-dataset",vertexDatasetName:e}}else{throw new Error(`Unsupported string source for Vertex AI: ${e}`)}}else{if(e.startsWith("files/")){n={fileName:e}}else{throw new Error(`Unsupported string source for Gemini API: ${e}`)}}}else if(Array.isArray(e)){if(t.isVertexAI()){throw new Error("InlinedRequest[] is not supported in Vertex AI.")}n={inlinedRequests:e}}else{n=e}const i=[n.gcsUri,n.bigqueryUri,n.vertexDatasetName].filter(Boolean).length;const r=[n.inlinedRequests,n.fileName].filter(Boolean).length;if(t.isVertexAI()){if(r>0||i!==1){throw new Error("Exactly one of `gcsUri`, `bigqueryUri`, or `vertexDatasetName` must be set for Vertex AI.")}}else{if(i>0||r!==1){throw new Error("Exactly one of `inlinedRequests`, `fileName`, must be set for Gemini API.")}}return n}function iE(t){if(typeof t!=="string"){return t}const e=t;if(e.startsWith("gs://")){return{format:"jsonl",gcsUri:e}}else if(e.startsWith("bq://")){return{format:"bigquery",bigqueryUri:e}}else{throw new Error(`Unsupported destination: ${e}`)}}function wf(t){if(typeof t!=="object"||t===null){return{}}const e=t;const n=e["inlinedResponses"];if(typeof n!=="object"||n===null){return t}const i=n;const r=i["inlinedResponses"];if(!Array.isArray(r)||r.length===0){return t}let o=false;for(const l of r){if(typeof l!=="object"||l===null){continue}const u=l;const c=u["response"];if(typeof c!=="object"||c===null){continue}const d=c;if(d["embedding"]!==void 0){o=true;break}}if(o){e["inlinedEmbedContentResponses"]=e["inlinedResponses"];delete e["inlinedResponses"]}return t}function rn(t,e){const n=e;if(!t.isVertexAI()){const r=/batches\/[^/]+$/;if(r.test(n)){return n.split("/").pop()}else{throw new Error(`Invalid batch job name: ${n}.`)}}const i=/^projects\/[^/]+\/locations\/[^/]+\/batchPredictionJobs\/[^/]+$/;if(i.test(n)){return n.split("/").pop()}else if(/^\d+$/.test(n)){return n}else{throw new Error(`Invalid batch job name: ${n}.`)}}function Rf(t){const e=t;if(e==="BATCH_STATE_UNSPECIFIED"){return"JOB_STATE_UNSPECIFIED"}else if(e==="BATCH_STATE_PENDING"){return"JOB_STATE_PENDING"}else if(e==="BATCH_STATE_RUNNING"){return"JOB_STATE_RUNNING"}else if(e==="BATCH_STATE_SUCCEEDED"){return"JOB_STATE_SUCCEEDED"}else if(e==="BATCH_STATE_FAILED"){return"JOB_STATE_FAILED"}else if(e==="BATCH_STATE_CANCELLED"){return"JOB_STATE_CANCELLED"}else if(e==="BATCH_STATE_EXPIRED"){return"JOB_STATE_EXPIRED"}else{return e}}function rE(t){return t.includes("gemini")&&t!=="gemini-embedding-001"||t.includes("maas")}function oE(t){const e={};const n=s(t,["apiKey"]);if(n!=null){a(e,["apiKey"],n)}if(s(t,["apiKeyConfig"])!==void 0){throw new Error("apiKeyConfig parameter is not supported in Gemini API.")}if(s(t,["authType"])!==void 0){throw new Error("authType parameter is not supported in Gemini API.")}if(s(t,["googleServiceAccountConfig"])!==void 0){throw new Error("googleServiceAccountConfig parameter is not supported in Gemini API.")}if(s(t,["httpBasicAuthConfig"])!==void 0){throw new Error("httpBasicAuthConfig parameter is not supported in Gemini API.")}if(s(t,["oauthConfig"])!==void 0){throw new Error("oauthConfig parameter is not supported in Gemini API.")}if(s(t,["oidcConfig"])!==void 0){throw new Error("oidcConfig parameter is not supported in Gemini API.")}return e}function sE(t){const e={};const n=s(t,["responsesFile"]);if(n!=null){a(e,["fileName"],n)}const i=s(t,["inlinedResponses","inlinedResponses"]);if(i!=null){let o=i;if(Array.isArray(o)){o=o.map(l=>{return qE(l)})}a(e,["inlinedResponses"],o)}const r=s(t,["inlinedEmbedContentResponses","inlinedResponses"]);if(r!=null){let o=r;if(Array.isArray(o)){o=o.map(l=>{return l})}a(e,["inlinedEmbedContentResponses"],o)}return e}function aE(t){const e={};const n=s(t,["predictionsFormat"]);if(n!=null){a(e,["format"],n)}const i=s(t,["gcsDestination","outputUriPrefix"]);if(i!=null){a(e,["gcsUri"],i)}const r=s(t,["bigqueryDestination","outputUri"]);if(r!=null){a(e,["bigqueryUri"],r)}const o=s(t,["vertexMultimodalDatasetDestination"]);if(o!=null){a(e,["vertexDataset"],QE(o))}return e}function lE(t){const e={};const n=s(t,["format"]);if(n!=null){a(e,["predictionsFormat"],n)}const i=s(t,["gcsUri"]);if(i!=null){a(e,["gcsDestination","outputUriPrefix"],i)}const r=s(t,["bigqueryUri"]);if(r!=null){a(e,["bigqueryDestination","outputUri"],r)}if(s(t,["fileName"])!==void 0){throw new Error("fileName parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).")}if(s(t,["inlinedResponses"])!==void 0){throw new Error("inlinedResponses parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).")}if(s(t,["inlinedEmbedContentResponses"])!==void 0){throw new Error("inlinedEmbedContentResponses parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).")}const o=s(t,["vertexDataset"]);if(o!=null){a(e,["vertexMultimodalDatasetDestination"],ZE(o))}return e}function Gi(t){const e={};const n=s(t,["name"]);if(n!=null){a(e,["name"],n)}const i=s(t,["metadata","displayName"]);if(i!=null){a(e,["displayName"],i)}const r=s(t,["metadata","state"]);if(r!=null){a(e,["state"],Rf(r))}const o=s(t,["metadata","createTime"]);if(o!=null){a(e,["createTime"],o)}const l=s(t,["metadata","endTime"]);if(l!=null){a(e,["endTime"],l)}const u=s(t,["metadata","updateTime"]);if(u!=null){a(e,["updateTime"],u)}const c=s(t,["metadata","model"]);if(c!=null){a(e,["model"],c)}const d=s(t,["metadata","output"]);if(d!=null){a(e,["dest"],sE(wf(d)))}return e}function Zs(t){const e={};const n=s(t,["name"]);if(n!=null){a(e,["name"],n)}const i=s(t,["displayName"]);if(i!=null){a(e,["displayName"],i)}const r=s(t,["state"]);if(r!=null){a(e,["state"],Rf(r))}const o=s(t,["error"]);if(o!=null){a(e,["error"],o)}const l=s(t,["createTime"]);if(l!=null){a(e,["createTime"],l)}const u=s(t,["startTime"]);if(u!=null){a(e,["startTime"],u)}const c=s(t,["endTime"]);if(c!=null){a(e,["endTime"],c)}const d=s(t,["updateTime"]);if(d!=null){a(e,["updateTime"],d)}const f=s(t,["model"]);if(f!=null){a(e,["model"],f)}const p=s(t,["inputConfig"]);if(p!=null){a(e,["src"],uE(p))}const h=s(t,["outputConfig"]);if(h!=null){a(e,["dest"],aE(wf(h)))}const m=s(t,["completionStats"]);if(m!=null){a(e,["completionStats"],m)}const _=s(t,["outputInfo"]);if(_!=null){a(e,["outputInfo"],_)}return e}function uE(t){const e={};const n=s(t,["instancesFormat"]);if(n!=null){a(e,["format"],n)}const i=s(t,["gcsSource","uris"]);if(i!=null){a(e,["gcsUri"],i)}const r=s(t,["bigquerySource","inputUri"]);if(r!=null){a(e,["bigqueryUri"],r)}const o=s(t,["vertexMultimodalDatasetSource","datasetName"]);if(o!=null){a(e,["vertexDatasetName"],o)}return e}function cE(t,e){const n={};if(s(e,["format"])!==void 0){throw new Error("format parameter is not supported in Gemini API.")}if(s(e,["gcsUri"])!==void 0){throw new Error("gcsUri parameter is not supported in Gemini API.")}if(s(e,["bigqueryUri"])!==void 0){throw new Error("bigqueryUri parameter is not supported in Gemini API.")}const i=s(e,["fileName"]);if(i!=null){a(n,["fileName"],i)}const r=s(e,["inlinedRequests"]);if(r!=null){let o=r;if(Array.isArray(o)){o=o.map(l=>{return FE(t,l)})}a(n,["requests","requests"],o)}if(s(e,["vertexDatasetName"])!==void 0){throw new Error("vertexDatasetName parameter is not supported in Gemini API.")}return n}function dE(t){const e={};const n=s(t,["format"]);if(n!=null){a(e,["instancesFormat"],n)}const i=s(t,["gcsUri"]);if(i!=null){a(e,["gcsSource","uris"],i)}const r=s(t,["bigqueryUri"]);if(r!=null){a(e,["bigquerySource","inputUri"],r)}if(s(t,["fileName"])!==void 0){throw new Error("fileName parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).")}if(s(t,["inlinedRequests"])!==void 0){throw new Error("inlinedRequests parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).")}const o=s(t,["vertexDatasetName"]);if(o!=null){a(e,["vertexMultimodalDatasetSource","datasetName"],o)}return e}function fE(t){const e={};const n=s(t,["data"]);if(n!=null){a(e,["data"],n)}if(s(t,["displayName"])!==void 0){throw new Error("displayName parameter is not supported in Gemini API.")}const i=s(t,["mimeType"]);if(i!=null){a(e,["mimeType"],i)}return e}function pE(t,e){const n={};const i=s(e,["name"]);if(i!=null){a(n,["_url","name"],rn(t,i))}return n}function hE(t,e){const n={};const i=s(e,["name"]);if(i!=null){a(n,["_url","name"],rn(t,i))}return n}function gE(t){const e={};const n=s(t,["content"]);if(n!=null){a(e,["content"],n)}const i=s(t,["citationMetadata"]);if(i!=null){a(e,["citationMetadata"],mE(i))}const r=s(t,["tokenCount"]);if(r!=null){a(e,["tokenCount"],r)}const o=s(t,["finishReason"]);if(o!=null){a(e,["finishReason"],o)}const l=s(t,["groundingMetadata"]);if(l!=null){a(e,["groundingMetadata"],l)}const u=s(t,["avgLogprobs"]);if(u!=null){a(e,["avgLogprobs"],u)}const c=s(t,["index"]);if(c!=null){a(e,["index"],c)}const d=s(t,["logprobsResult"]);if(d!=null){a(e,["logprobsResult"],d)}const f=s(t,["safetyRatings"]);if(f!=null){let h=f;if(Array.isArray(h)){h=h.map(m=>{return m})}a(e,["safetyRatings"],h)}const p=s(t,["urlContextMetadata"]);if(p!=null){a(e,["urlContextMetadata"],p)}return e}function mE(t){const e={};const n=s(t,["citationSources"]);if(n!=null){let i=n;if(Array.isArray(i)){i=i.map(r=>{return r})}a(e,["citations"],i)}return e}function Pf(t){const e={};const n=s(t,["parts"]);if(n!=null){let r=n;if(Array.isArray(r)){r=r.map(o=>{return WE(o)})}a(e,["parts"],r)}const i=s(t,["role"]);if(i!=null){a(e,["role"],i)}return e}function yE(t,e){const n={};const i=s(t,["displayName"]);if(e!==void 0&&i!=null){a(e,["batch","displayName"],i)}if(s(t,["dest"])!==void 0){throw new Error("dest parameter is not supported in Gemini API.")}const r=s(t,["webhookConfig"]);if(e!==void 0&&r!=null){a(e,["batch","webhookConfig"],r)}return n}function EE(t,e){const n={};const i=s(t,["displayName"]);if(e!==void 0&&i!=null){a(e,["displayName"],i)}const r=s(t,["dest"]);if(e!==void 0&&r!=null){a(e,["outputConfig"],lE(iE(r)))}if(s(t,["webhookConfig"])!==void 0){throw new Error("webhookConfig parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).")}return n}function Hd(t,e){const n={};const i=s(e,["model"]);if(i!=null){a(n,["_url","model"],j(t,i))}const r=s(e,["src"]);if(r!=null){a(n,["batch","inputConfig"],cE(t,If(t,r)))}const o=s(e,["config"]);if(o!=null){yE(o,n)}return n}function _E(t,e){const n={};const i=s(e,["model"]);if(i!=null){a(n,["model"],j(t,i))}const r=s(e,["src"]);if(r!=null){a(n,["inputConfig"],dE(If(t,r)))}const o=s(e,["config"]);if(o!=null){EE(o,n)}return n}function TE(t,e){const n={};const i=s(t,["displayName"]);if(e!==void 0&&i!=null){a(e,["batch","displayName"],i)}return n}function AE(t,e){const n={};const i=s(e,["model"]);if(i!=null){a(n,["_url","model"],j(t,i))}const r=s(e,["src"]);if(r!=null){a(n,["batch","inputConfig"],PE(t,r))}const o=s(e,["config"]);if(o!=null){TE(o,n)}return n}function CE(t,e){const n={};const i=s(e,["name"]);if(i!=null){a(n,["_url","name"],rn(t,i))}return n}function vE(t,e){const n={};const i=s(e,["name"]);if(i!=null){a(n,["_url","name"],rn(t,i))}return n}function SE(t){const e={};const n=s(t,["sdkHttpResponse"]);if(n!=null){a(e,["sdkHttpResponse"],n)}const i=s(t,["name"]);if(i!=null){a(e,["name"],i)}const r=s(t,["done"]);if(r!=null){a(e,["done"],r)}const o=s(t,["error"]);if(o!=null){a(e,["error"],o)}return e}function IE(t){const e={};const n=s(t,["sdkHttpResponse"]);if(n!=null){a(e,["sdkHttpResponse"],n)}const i=s(t,["name"]);if(i!=null){a(e,["name"],i)}const r=s(t,["done"]);if(r!=null){a(e,["done"],r)}const o=s(t,["error"]);if(o!=null){a(e,["error"],o)}return e}function wE(t,e){const n={};const i=s(e,["contents"]);if(i!=null){let o=La(t,i);if(Array.isArray(o)){o=o.map(l=>{return l})}a(n,["requests[]","request","content"],o)}const r=s(e,["config"]);if(r!=null){a(n,["_self"],RE(r,n));Gy(n,{"requests[].*":"requests[].request.*"})}return n}function RE(t,e){const n={};const i=s(t,["taskType"]);if(e!==void 0&&i!=null){a(e,["requests[]","taskType"],i)}const r=s(t,["title"]);if(e!==void 0&&r!=null){a(e,["requests[]","title"],r)}const o=s(t,["outputDimensionality"]);if(e!==void 0&&o!=null){a(e,["requests[]","outputDimensionality"],o)}if(s(t,["mimeType"])!==void 0){throw new Error("mimeType parameter is not supported in Gemini API.")}if(s(t,["autoTruncate"])!==void 0){throw new Error("autoTruncate parameter is not supported in Gemini API.")}if(s(t,["documentOcr"])!==void 0){throw new Error("documentOcr parameter is not supported in Gemini API.")}if(s(t,["audioTrackExtraction"])!==void 0){throw new Error("audioTrackExtraction parameter is not supported in Gemini API.")}return n}function PE(t,e){const n={};const i=s(e,["fileName"]);if(i!=null){a(n,["file_name"],i)}const r=s(e,["inlinedRequests"]);if(r!=null){a(n,["requests"],wE(t,r))}return n}function NE(t){const e={};if(s(t,["displayName"])!==void 0){throw new Error("displayName parameter is not supported in Gemini API.")}const n=s(t,["fileUri"]);if(n!=null){a(e,["fileUri"],n)}const i=s(t,["mimeType"]);if(i!=null){a(e,["mimeType"],i)}return e}function ME(t){const e={};const n=s(t,["id"]);if(n!=null){a(e,["id"],n)}const i=s(t,["args"]);if(i!=null){a(e,["args"],i)}const r=s(t,["name"]);if(r!=null){a(e,["name"],r)}if(s(t,["partialArgs"])!==void 0){throw new Error("partialArgs parameter is not supported in Gemini API.")}if(s(t,["willContinue"])!==void 0){throw new Error("willContinue parameter is not supported in Gemini API.")}return e}function kE(t){const e={};const n=s(t,["allowedFunctionNames"]);if(n!=null){a(e,["allowedFunctionNames"],n)}const i=s(t,["mode"]);if(i!=null){a(e,["mode"],i)}if(s(t,["streamFunctionCallArguments"])!==void 0){throw new Error("streamFunctionCallArguments parameter is not supported in Gemini API.")}return e}function xE(t,e,n){const i={};const r=s(e,["systemInstruction"]);if(n!==void 0&&r!=null){a(n,["systemInstruction"],Pf(he(r)))}const o=s(e,["temperature"]);if(o!=null){a(i,["temperature"],o)}const l=s(e,["topP"]);if(l!=null){a(i,["topP"],l)}const u=s(e,["topK"]);if(u!=null){a(i,["topK"],u)}const c=s(e,["candidateCount"]);if(c!=null){a(i,["candidateCount"],c)}const d=s(e,["maxOutputTokens"]);if(d!=null){a(i,["maxOutputTokens"],d)}const f=s(e,["stopSequences"]);if(f!=null){a(i,["stopSequences"],f)}const p=s(e,["responseLogprobs"]);if(p!=null){a(i,["responseLogprobs"],p)}const h=s(e,["logprobs"]);if(h!=null){a(i,["logprobs"],h)}const m=s(e,["presencePenalty"]);if(m!=null){a(i,["presencePenalty"],m)}const _=s(e,["frequencyPenalty"]);if(_!=null){a(i,["frequencyPenalty"],_)}const A=s(e,["seed"]);if(A!=null){a(i,["seed"],A)}const T=s(e,["responseMimeType"]);if(T!=null){a(i,["responseMimeType"],T)}const v=s(e,["responseSchema"]);if(v!=null){a(i,["responseSchema"],Ga(v))}const G=s(e,["responseJsonSchema"]);if(G!=null){a(i,["responseJsonSchema"],G)}if(s(e,["routingConfig"])!==void 0){throw new Error("routingConfig parameter is not supported in Gemini API.")}if(s(e,["modelSelectionConfig"])!==void 0){throw new Error("modelSelectionConfig parameter is not supported in Gemini API.")}const D=s(e,["safetySettings"]);if(n!==void 0&&D!=null){let ee=D;if(Array.isArray(ee)){ee=ee.map(re=>{return YE(re)})}a(n,["safetySettings"],ee)}const O=s(e,["tools"]);if(n!==void 0&&O!=null){let ee=nn(O);if(Array.isArray(ee)){ee=ee.map(re=>{return XE(tn(re))})}a(n,["tools"],ee)}const L=s(e,["toolConfig"]);if(n!==void 0&&L!=null){a(n,["toolConfig"],zE(L))}if(s(e,["labels"])!==void 0){throw new Error("labels parameter is not supported in Gemini API.")}const R=s(e,["cachedContent"]);if(n!==void 0&&R!=null){a(n,["cachedContent"],lt(t,R))}const q=s(e,["responseModalities"]);if(q!=null){a(i,["responseModalities"],q)}const V=s(e,["mediaResolution"]);if(V!=null){a(i,["mediaResolution"],V)}const k=s(e,["speechConfig"]);if(k!=null){a(i,["speechConfig"],Oa(k))}if(s(e,["audioTimestamp"])!==void 0){throw new Error("audioTimestamp parameter is not supported in Gemini API.")}const $=s(e,["thinkingConfig"]);if($!=null){a(i,["thinkingConfig"],$)}const Y=s(e,["imageConfig"]);if(Y!=null){a(i,["imageConfig"],bE(Y))}const Q=s(e,["enableEnhancedCivicAnswers"]);if(Q!=null){a(i,["enableEnhancedCivicAnswers"],Q)}if(s(e,["modelArmorConfig"])!==void 0){throw new Error("modelArmorConfig parameter is not supported in Gemini API.")}const oe=s(e,["serviceTier"]);if(n!==void 0&&oe!=null){a(n,["serviceTier"],oe)}return i}function DE(t){const e={};const n=s(t,["sdkHttpResponse"]);if(n!=null){a(e,["sdkHttpResponse"],n)}const i=s(t,["candidates"]);if(i!=null){let d=i;if(Array.isArray(d)){d=d.map(f=>{return gE(f)})}a(e,["candidates"],d)}const r=s(t,["modelVersion"]);if(r!=null){a(e,["modelVersion"],r)}const o=s(t,["promptFeedback"]);if(o!=null){a(e,["promptFeedback"],o)}const l=s(t,["responseId"]);if(l!=null){a(e,["responseId"],l)}const u=s(t,["usageMetadata"]);if(u!=null){a(e,["usageMetadata"],u)}const c=s(t,["modelStatus"]);if(c!=null){a(e,["modelStatus"],c)}return e}function UE(t,e){const n={};const i=s(e,["name"]);if(i!=null){a(n,["_url","name"],rn(t,i))}return n}function LE(t,e){const n={};const i=s(e,["name"]);if(i!=null){a(n,["_url","name"],rn(t,i))}return n}function GE(t){const e={};const n=s(t,["authConfig"]);if(n!=null){a(e,["authConfig"],oE(n))}const i=s(t,["enableWidget"]);if(i!=null){a(e,["enableWidget"],i)}return e}function OE(t){const e={};const n=s(t,["searchTypes"]);if(n!=null){a(e,["searchTypes"],n)}if(s(t,["blockingConfidence"])!==void 0){throw new Error("blockingConfidence parameter is not supported in Gemini API.")}if(s(t,["excludeDomains"])!==void 0){throw new Error("excludeDomains parameter is not supported in Gemini API.")}const i=s(t,["timeRangeFilter"]);if(i!=null){a(e,["timeRangeFilter"],i)}return e}function bE(t){const e={};const n=s(t,["aspectRatio"]);if(n!=null){a(e,["aspectRatio"],n)}const i=s(t,["imageSize"]);if(i!=null){a(e,["imageSize"],i)}if(s(t,["personGeneration"])!==void 0){throw new Error("personGeneration parameter is not supported in Gemini API.")}if(s(t,["prominentPeople"])!==void 0){throw new Error("prominentPeople parameter is not supported in Gemini API.")}if(s(t,["outputMimeType"])!==void 0){throw new Error("outputMimeType parameter is not supported in Gemini API.")}if(s(t,["outputCompressionQuality"])!==void 0){throw new Error("outputCompressionQuality parameter is not supported in Gemini API.")}if(s(t,["imageOutputOptions"])!==void 0){throw new Error("imageOutputOptions parameter is not supported in Gemini API.")}return e}function FE(t,e){const n={};const i=s(e,["model"]);if(i!=null){a(n,["request","model"],j(t,i))}const r=s(e,["contents"]);if(r!=null){let u=Ae(r);if(Array.isArray(u)){u=u.map(c=>{return Pf(c)})}a(n,["request","contents"],u)}const o=s(e,["metadata"]);if(o!=null){a(n,["metadata"],o)}const l=s(e,["config"]);if(l!=null){a(n,["request","generationConfig"],xE(t,l,s(n,["request"],{})))}return n}function qE(t){const e={};const n=s(t,["response"]);if(n!=null){a(e,["response"],DE(n))}const i=s(t,["metadata"]);if(i!=null){a(e,["metadata"],i)}const r=s(t,["error"]);if(r!=null){a(e,["error"],r)}return e}function HE(t,e){const n={};const i=s(t,["pageSize"]);if(e!==void 0&&i!=null){a(e,["_query","pageSize"],i)}const r=s(t,["pageToken"]);if(e!==void 0&&r!=null){a(e,["_query","pageToken"],r)}if(s(t,["filter"])!==void 0){throw new Error("filter parameter is not supported in Gemini API.")}return n}function VE(t,e){const n={};const i=s(t,["pageSize"]);if(e!==void 0&&i!=null){a(e,["_query","pageSize"],i)}const r=s(t,["pageToken"]);if(e!==void 0&&r!=null){a(e,["_query","pageToken"],r)}const o=s(t,["filter"]);if(e!==void 0&&o!=null){a(e,["_query","filter"],o)}return n}function BE(t){const e={};const n=s(t,["config"]);if(n!=null){HE(n,e)}return e}function $E(t){const e={};const n=s(t,["config"]);if(n!=null){VE(n,e)}return e}function JE(t){const e={};const n=s(t,["sdkHttpResponse"]);if(n!=null){a(e,["sdkHttpResponse"],n)}const i=s(t,["nextPageToken"]);if(i!=null){a(e,["nextPageToken"],i)}const r=s(t,["operations"]);if(r!=null){let o=r;if(Array.isArray(o)){o=o.map(l=>{return Gi(l)})}a(e,["batchJobs"],o)}return e}function KE(t){const e={};const n=s(t,["sdkHttpResponse"]);if(n!=null){a(e,["sdkHttpResponse"],n)}const i=s(t,["nextPageToken"]);if(i!=null){a(e,["nextPageToken"],i)}const r=s(t,["batchPredictionJobs"]);if(r!=null){let o=r;if(Array.isArray(o)){o=o.map(l=>{return Zs(l)})}a(e,["batchJobs"],o)}return e}function WE(t){const e={};const n=s(t,["mediaResolution"]);if(n!=null){a(e,["mediaResolution"],n)}const i=s(t,["codeExecutionResult"]);if(i!=null){a(e,["codeExecutionResult"],i)}const r=s(t,["executableCode"]);if(r!=null){a(e,["executableCode"],r)}const o=s(t,["fileData"]);if(o!=null){a(e,["fileData"],NE(o))}const l=s(t,["functionCall"]);if(l!=null){a(e,["functionCall"],ME(l))}const u=s(t,["functionResponse"]);if(u!=null){a(e,["functionResponse"],u)}const c=s(t,["inlineData"]);if(c!=null){a(e,["inlineData"],fE(c))}const d=s(t,["text"]);if(d!=null){a(e,["text"],d)}const f=s(t,["thought"]);if(f!=null){a(e,["thought"],f)}const p=s(t,["thoughtSignature"]);if(p!=null){a(e,["thoughtSignature"],p)}const h=s(t,["videoMetadata"]);if(h!=null){a(e,["videoMetadata"],h)}const m=s(t,["toolCall"]);if(m!=null){a(e,["toolCall"],m)}const _=s(t,["toolResponse"]);if(_!=null){a(e,["toolResponse"],_)}const A=s(t,["partMetadata"]);if(A!=null){a(e,["partMetadata"],A)}return e}function YE(t){const e={};const n=s(t,["category"]);if(n!=null){a(e,["category"],n)}if(s(t,["method"])!==void 0){throw new Error("method parameter is not supported in Gemini API.")}const i=s(t,["threshold"]);if(i!=null){a(e,["threshold"],i)}return e}function zE(t){const e={};const n=s(t,["retrievalConfig"]);if(n!=null){a(e,["retrievalConfig"],n)}const i=s(t,["functionCallingConfig"]);if(i!=null){a(e,["functionCallingConfig"],kE(i))}const r=s(t,["includeServerSideToolInvocations"]);if(r!=null){a(e,["includeServerSideToolInvocations"],r)}return e}function XE(t){const e={};if(s(t,["retrieval"])!==void 0){throw new Error("retrieval parameter is not supported in Gemini API.")}const n=s(t,["computerUse"]);if(n!=null){a(e,["computerUse"],n)}const i=s(t,["fileSearch"]);if(i!=null){a(e,["fileSearch"],i)}const r=s(t,["googleSearch"]);if(r!=null){a(e,["googleSearch"],OE(r))}const o=s(t,["googleMaps"]);if(o!=null){a(e,["googleMaps"],GE(o))}const l=s(t,["codeExecution"]);if(l!=null){a(e,["codeExecution"],l)}if(s(t,["enterpriseWebSearch"])!==void 0){throw new Error("enterpriseWebSearch parameter is not supported in Gemini API.")}const u=s(t,["functionDeclarations"]);if(u!=null){let p=u;if(Array.isArray(p)){p=p.map(h=>{return h})}a(e,["functionDeclarations"],p)}const c=s(t,["googleSearchRetrieval"]);if(c!=null){a(e,["googleSearchRetrieval"],c)}if(s(t,["parallelAiSearch"])!==void 0){throw new Error("parallelAiSearch parameter is not supported in Gemini API.")}const d=s(t,["urlContext"]);if(d!=null){a(e,["urlContext"],d)}const f=s(t,["mcpServers"]);if(f!=null){let p=f;if(Array.isArray(p)){p=p.map(h=>{return h})}a(e,["mcpServers"],p)}return e}function QE(t){const e={};const n=s(t,["bigqueryDestination","outputUri"]);if(n!=null){a(e,["bigqueryDestination"],n)}const i=s(t,["displayName"]);if(i!=null){a(e,["displayName"],i)}return e}function ZE(t){const e={};const n=s(t,["bigqueryDestination"]);if(n!=null){a(e,["bigqueryDestination","outputUri"],n)}const i=s(t,["displayName"]);if(i!=null){a(e,["displayName"],i)}return e}var st;(function(t){t["PAGED_ITEM_BATCH_JOBS"]="batchJobs";t["PAGED_ITEM_MODELS"]="models";t["PAGED_ITEM_TUNING_JOBS"]="tuningJobs";t["PAGED_ITEM_FILES"]="files";t["PAGED_ITEM_CACHED_CONTENTS"]="cachedContents";t["PAGED_ITEM_FILE_SEARCH_STORES"]="fileSearchStores";t["PAGED_ITEM_DOCUMENTS"]="documents"})(st||(st={}));var at=class{constructor(e,n,i,r){this.pageInternal=[];this.paramsInternal={};this.requestInternal=n;this.init(e,i,r)}init(e,n,i){var r,o;this.nameInternal=e;this.pageInternal=n[this.nameInternal]||[];this.sdkHttpResponseInternal=n===null||n===void 0?void 0:n.sdkHttpResponse;this.idxInternal=0;let l={config:{}};if(!i||Object.keys(i).length===0){l={config:{}}}else if(typeof i==="object"){l=Object.assign({},i)}else{l=i}if(l["config"]){l["config"]["pageToken"]=n["nextPageToken"]}this.paramsInternal=l;this.pageInternalSize=(o=(r=l["config"])===null||r===void 0?void 0:r["pageSize"])!==null&&o!==void 0?o:this.pageInternal.length}initNextPage(e){this.init(this.nameInternal,e,this.paramsInternal)}get page(){return this.pageInternal}get name(){return this.nameInternal}get pageSize(){return this.pageInternalSize}get sdkHttpResponse(){return this.sdkHttpResponseInternal}get params(){return this.paramsInternal}get pageLength(){return this.pageInternal.length}getItem(e){return this.pageInternal[e]}[Symbol.asyncIterator](){return{next:async()=>{if(this.idxInternal>=this.pageLength){if(this.hasNextPage()){await this.nextPage()}else{return{value:void 0,done:true}}}const e=this.getItem(this.idxInternal);this.idxInternal+=1;return{value:e,done:false}},return:async()=>{return{value:void 0,done:true}}}}async nextPage(){if(!this.hasNextPage()){throw new Error("No more pages to fetch.")}const e=await this.requestInternal(this.params);this.initNextPage(e);return this.page}hasNextPage(){var e;if(((e=this.params["config"])===null||e===void 0?void 0:e["pageToken"])!==void 0){return true}return false}};var js=class extends We{constructor(e){super();this.apiClient=e;this.list=async(n={})=>{return new at(st.PAGED_ITEM_BATCH_JOBS,i=>this.listInternal(i),await this.listInternal(n),n)};this.create=async n=>{if(this.apiClient.isVertexAI()){n.config=this.formatDestination(n.src,n.config)}return this.createInternal(n)};this.createEmbeddings=async n=>{console.warn("batches.createEmbeddings() is experimental and may change without notice.");if(this.apiClient.isVertexAI()){throw new Error("Gemini Enterprise Agent Platform (previously known as Vertex AI) does not support batches.createEmbeddings.")}return this.createEmbeddingsInternal(n)}}createInlinedGenerateContentRequest(e){const n=Hd(this.apiClient,e);const i=n["_url"];const r=H("{model}:batchGenerateContent",i);const o=n["batch"];const l=o["inputConfig"];const u=l["requests"];const c=u["requests"];const d=[];for(const f of c){const p=Object.assign({},f);if(p["systemInstruction"]){const h=p["systemInstruction"];delete p["systemInstruction"];const m=p["request"];m["systemInstruction"]=h;p["request"]=m}d.push(p)}u["requests"]=d;delete n["config"];delete n["_url"];delete n["_query"];return{path:r,body:n}}getGcsUri(e){if(typeof e==="string"){return e.startsWith("gs://")?e:void 0}if(!Array.isArray(e)&&e.gcsUri&&e.gcsUri.length>0){return e.gcsUri[0]}return void 0}getBigqueryUri(e){if(typeof e==="string"){return e.startsWith("bq://")?e:void 0}if(!Array.isArray(e)){return e.bigqueryUri}return void 0}formatDestination(e,n){const i=n?Object.assign({},n):{};const r=Date.now().toString();if(!i.displayName){i.displayName=`genaiBatchJob_${r}`}if(i.dest===void 0){const o=this.getGcsUri(e);const l=this.getBigqueryUri(e);if(o){if(o.endsWith(".jsonl")){i.dest=`${o.slice(0,-6)}/dest`}else{i.dest=`${o}_dest_${r}`}}else if(l){i.dest=`${l}_dest_${r}`}else{throw new Error("Unsupported source for Gemini Enterprise Agent Platform (previously known as Vertex AI): No GCS or BigQuery URI found.")}}return i}async createInternal(e){var n,i,r,o;let l;let u="";let c={};if(this.apiClient.isVertexAI()){const d=_E(this.apiClient,e);u=H("batchPredictionJobs",d["_url"]);c=d["_query"];delete d["_url"];delete d["_query"];l=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>{return f.json()});return l.then(f=>{const p=Zs(f);return p})}else{const d=Hd(this.apiClient,e);u=H("{model}:batchGenerateContent",d["_url"]);c=d["_query"];delete d["_url"];delete d["_query"];l=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(r=e.config)===null||r===void 0?void 0:r.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>{return f.json()});return l.then(f=>{const p=Gi(f);return p})}}async createEmbeddingsInternal(e){var n,i;let r;let o="";let l={};if(this.apiClient.isVertexAI()){throw new Error("This method is only supported by the Gemini Developer API.")}else{const u=AE(this.apiClient,e);o=H("{model}:asyncBatchEmbedContent",u["_url"]);l=u["_query"];delete u["_url"];delete u["_query"];r=this.apiClient.request({path:o,queryParams:l,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(c=>{return c.json()});return r.then(c=>{const d=Gi(c);return d})}}async get(e){var n,i,r,o;let l;let u="";let c={};if(this.apiClient.isVertexAI()){const d=LE(this.apiClient,e);u=H("batchPredictionJobs/{name}",d["_url"]);c=d["_query"];delete d["_url"];delete d["_query"];l=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>{return f.json()});return l.then(f=>{const p=Zs(f);return p})}else{const d=UE(this.apiClient,e);u=H("batches/{name}",d["_url"]);c=d["_query"];delete d["_url"];delete d["_query"];l=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(r=e.config)===null||r===void 0?void 0:r.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>{return f.json()});return l.then(f=>{const p=Gi(f);return p})}}async cancel(e){var n,i,r,o;let l="";let u={};if(this.apiClient.isVertexAI()){const c=hE(this.apiClient,e);l=H("batchPredictionJobs/{name}:cancel",c["_url"]);u=c["_query"];delete c["_url"];delete c["_query"];await this.apiClient.request({path:l,queryParams:u,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal})}else{const c=pE(this.apiClient,e);l=H("batches/{name}:cancel",c["_url"]);u=c["_query"];delete c["_url"];delete c["_query"];await this.apiClient.request({path:l,queryParams:u,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(r=e.config)===null||r===void 0?void 0:r.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal})}}async listInternal(e){var n,i,r,o;let l;let u="";let c={};if(this.apiClient.isVertexAI()){const d=$E(e);u=H("batchPredictionJobs",d["_url"]);c=d["_query"];delete d["_url"];delete d["_query"];l=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>{return f.json().then(p=>{const h=p;h.sdkHttpResponse={headers:f.headers};return h})});return l.then(f=>{const p=KE(f);const h=new zi;Object.assign(h,p);return h})}else{const d=BE(e);u=H("batches",d["_url"]);c=d["_query"];delete d["_url"];delete d["_query"];l=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(r=e.config)===null||r===void 0?void 0:r.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>{return f.json().then(p=>{const h=p;h.sdkHttpResponse={headers:f.headers};return h})});return l.then(f=>{const p=JE(f);const h=new zi;Object.assign(h,p);return h})}}async delete(e){var n,i,r,o;let l;let u="";let c={};if(this.apiClient.isVertexAI()){const d=vE(this.apiClient,e);u=H("batchPredictionJobs/{name}",d["_url"]);c=d["_query"];delete d["_url"];delete d["_query"];l=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"DELETE",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>{return f.json().then(p=>{const h=p;h.sdkHttpResponse={headers:f.headers};return h})});return l.then(f=>{const p=IE(f);return p})}else{const d=CE(this.apiClient,e);u=H("batches/{name}",d["_url"]);c=d["_query"];delete d["_url"];delete d["_query"];l=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"DELETE",httpOptions:(r=e.config)===null||r===void 0?void 0:r.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>{return f.json().then(p=>{const h=p;h.sdkHttpResponse={headers:f.headers};return h})});return l.then(f=>{const p=SE(f);return p})}}};function jE(t){const e={};const n=s(t,["apiKey"]);if(n!=null){a(e,["apiKey"],n)}if(s(t,["apiKeyConfig"])!==void 0){throw new Error("apiKeyConfig parameter is not supported in Gemini API.")}if(s(t,["authType"])!==void 0){throw new Error("authType parameter is not supported in Gemini API.")}if(s(t,["googleServiceAccountConfig"])!==void 0){throw new Error("googleServiceAccountConfig parameter is not supported in Gemini API.")}if(s(t,["httpBasicAuthConfig"])!==void 0){throw new Error("httpBasicAuthConfig parameter is not supported in Gemini API.")}if(s(t,["oauthConfig"])!==void 0){throw new Error("oauthConfig parameter is not supported in Gemini API.")}if(s(t,["oidcConfig"])!==void 0){throw new Error("oidcConfig parameter is not supported in Gemini API.")}return e}function e_(t){const e={};const n=s(t,["data"]);if(n!=null){a(e,["data"],n)}if(s(t,["displayName"])!==void 0){throw new Error("displayName parameter is not supported in Gemini API.")}const i=s(t,["mimeType"]);if(i!=null){a(e,["mimeType"],i)}return e}function Vd(t){const e={};const n=s(t,["parts"]);if(n!=null){let r=n;if(Array.isArray(r)){r=r.map(o=>{return v_(o)})}a(e,["parts"],r)}const i=s(t,["role"]);if(i!=null){a(e,["role"],i)}return e}function Bd(t){const e={};const n=s(t,["parts"]);if(n!=null){let r=n;if(Array.isArray(r)){r=r.map(o=>{return S_(o)})}a(e,["parts"],r)}const i=s(t,["role"]);if(i!=null){a(e,["role"],i)}return e}function t_(t,e){const n={};const i=s(t,["ttl"]);if(e!==void 0&&i!=null){a(e,["ttl"],i)}const r=s(t,["expireTime"]);if(e!==void 0&&r!=null){a(e,["expireTime"],r)}const o=s(t,["displayName"]);if(e!==void 0&&o!=null){a(e,["displayName"],o)}const l=s(t,["contents"]);if(e!==void 0&&l!=null){let f=Ae(l);if(Array.isArray(f)){f=f.map(p=>{return Vd(p)})}a(e,["contents"],f)}const u=s(t,["systemInstruction"]);if(e!==void 0&&u!=null){a(e,["systemInstruction"],Vd(he(u)))}const c=s(t,["tools"]);if(e!==void 0&&c!=null){let f=c;if(Array.isArray(f)){f=f.map(p=>{return R_(p)})}a(e,["tools"],f)}const d=s(t,["toolConfig"]);if(e!==void 0&&d!=null){a(e,["toolConfig"],I_(d))}if(s(t,["kmsKeyName"])!==void 0){throw new Error("kmsKeyName parameter is not supported in Gemini API.")}return n}function n_(t,e){const n={};const i=s(t,["ttl"]);if(e!==void 0&&i!=null){a(e,["ttl"],i)}const r=s(t,["expireTime"]);if(e!==void 0&&r!=null){a(e,["expireTime"],r)}const o=s(t,["displayName"]);if(e!==void 0&&o!=null){a(e,["displayName"],o)}const l=s(t,["contents"]);if(e!==void 0&&l!=null){let p=Ae(l);if(Array.isArray(p)){p=p.map(h=>{return Bd(h)})}a(e,["contents"],p)}const u=s(t,["systemInstruction"]);if(e!==void 0&&u!=null){a(e,["systemInstruction"],Bd(he(u)))}const c=s(t,["tools"]);if(e!==void 0&&c!=null){let p=c;if(Array.isArray(p)){p=p.map(h=>{return P_(h)})}a(e,["tools"],p)}const d=s(t,["toolConfig"]);if(e!==void 0&&d!=null){a(e,["toolConfig"],w_(d))}const f=s(t,["kmsKeyName"]);if(e!==void 0&&f!=null){a(e,["encryption_spec","kmsKeyName"],f)}return n}function i_(t,e){const n={};const i=s(e,["model"]);if(i!=null){a(n,["model"],gf(t,i))}const r=s(e,["config"]);if(r!=null){t_(r,n)}return n}function r_(t,e){const n={};const i=s(e,["model"]);if(i!=null){a(n,["model"],gf(t,i))}const r=s(e,["config"]);if(r!=null){n_(r,n)}return n}function o_(t,e){const n={};const i=s(e,["name"]);if(i!=null){a(n,["_url","name"],lt(t,i))}return n}function s_(t,e){const n={};const i=s(e,["name"]);if(i!=null){a(n,["_url","name"],lt(t,i))}return n}function a_(t){const e={};const n=s(t,["sdkHttpResponse"]);if(n!=null){a(e,["sdkHttpResponse"],n)}return e}function l_(t){const e={};const n=s(t,["sdkHttpResponse"]);if(n!=null){a(e,["sdkHttpResponse"],n)}return e}function u_(t){const e={};if(s(t,["displayName"])!==void 0){throw new Error("displayName parameter is not supported in Gemini API.")}const n=s(t,["fileUri"]);if(n!=null){a(e,["fileUri"],n)}const i=s(t,["mimeType"]);if(i!=null){a(e,["mimeType"],i)}return e}function c_(t){const e={};const n=s(t,["id"]);if(n!=null){a(e,["id"],n)}const i=s(t,["args"]);if(i!=null){a(e,["args"],i)}const r=s(t,["name"]);if(r!=null){a(e,["name"],r)}if(s(t,["partialArgs"])!==void 0){throw new Error("partialArgs parameter is not supported in Gemini API.")}if(s(t,["willContinue"])!==void 0){throw new Error("willContinue parameter is not supported in Gemini API.")}return e}function d_(t){const e={};const n=s(t,["allowedFunctionNames"]);if(n!=null){a(e,["allowedFunctionNames"],n)}const i=s(t,["mode"]);if(i!=null){a(e,["mode"],i)}if(s(t,["streamFunctionCallArguments"])!==void 0){throw new Error("streamFunctionCallArguments parameter is not supported in Gemini API.")}return e}function f_(t){const e={};const n=s(t,["description"]);if(n!=null){a(e,["description"],n)}const i=s(t,["name"]);if(i!=null){a(e,["name"],i)}const r=s(t,["parameters"]);if(r!=null){a(e,["parameters"],r)}const o=s(t,["parametersJsonSchema"]);if(o!=null){a(e,["parametersJsonSchema"],o)}const l=s(t,["response"]);if(l!=null){a(e,["response"],l)}const u=s(t,["responseJsonSchema"]);if(u!=null){a(e,["responseJsonSchema"],u)}if(s(t,["behavior"])!==void 0){throw new Error("behavior parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).")}return e}function p_(t,e){const n={};const i=s(e,["name"]);if(i!=null){a(n,["_url","name"],lt(t,i))}return n}function h_(t,e){const n={};const i=s(e,["name"]);if(i!=null){a(n,["_url","name"],lt(t,i))}return n}function g_(t){const e={};const n=s(t,["authConfig"]);if(n!=null){a(e,["authConfig"],jE(n))}const i=s(t,["enableWidget"]);if(i!=null){a(e,["enableWidget"],i)}return e}function m_(t){const e={};const n=s(t,["searchTypes"]);if(n!=null){a(e,["searchTypes"],n)}if(s(t,["blockingConfidence"])!==void 0){throw new Error("blockingConfidence parameter is not supported in Gemini API.")}if(s(t,["excludeDomains"])!==void 0){throw new Error("excludeDomains parameter is not supported in Gemini API.")}const i=s(t,["timeRangeFilter"]);if(i!=null){a(e,["timeRangeFilter"],i)}return e}function y_(t,e){const n={};const i=s(t,["pageSize"]);if(e!==void 0&&i!=null){a(e,["_query","pageSize"],i)}const r=s(t,["pageToken"]);if(e!==void 0&&r!=null){a(e,["_query","pageToken"],r)}return n}function E_(t,e){const n={};const i=s(t,["pageSize"]);if(e!==void 0&&i!=null){a(e,["_query","pageSize"],i)}const r=s(t,["pageToken"]);if(e!==void 0&&r!=null){a(e,["_query","pageToken"],r)}return n}function __(t){const e={};const n=s(t,["config"]);if(n!=null){y_(n,e)}return e}function T_(t){const e={};const n=s(t,["config"]);if(n!=null){E_(n,e)}return e}function A_(t){const e={};const n=s(t,["sdkHttpResponse"]);if(n!=null){a(e,["sdkHttpResponse"],n)}const i=s(t,["nextPageToken"]);if(i!=null){a(e,["nextPageToken"],i)}const r=s(t,["cachedContents"]);if(r!=null){let o=r;if(Array.isArray(o)){o=o.map(l=>{return l})}a(e,["cachedContents"],o)}return e}function C_(t){const e={};const n=s(t,["sdkHttpResponse"]);if(n!=null){a(e,["sdkHttpResponse"],n)}const i=s(t,["nextPageToken"]);if(i!=null){a(e,["nextPageToken"],i)}const r=s(t,["cachedContents"]);if(r!=null){let o=r;if(Array.isArray(o)){o=o.map(l=>{return l})}a(e,["cachedContents"],o)}return e}function v_(t){const e={};const n=s(t,["mediaResolution"]);if(n!=null){a(e,["mediaResolution"],n)}const i=s(t,["codeExecutionResult"]);if(i!=null){a(e,["codeExecutionResult"],i)}const r=s(t,["executableCode"]);if(r!=null){a(e,["executableCode"],r)}const o=s(t,["fileData"]);if(o!=null){a(e,["fileData"],u_(o))}const l=s(t,["functionCall"]);if(l!=null){a(e,["functionCall"],c_(l))}const u=s(t,["functionResponse"]);if(u!=null){a(e,["functionResponse"],u)}const c=s(t,["inlineData"]);if(c!=null){a(e,["inlineData"],e_(c))}const d=s(t,["text"]);if(d!=null){a(e,["text"],d)}const f=s(t,["thought"]);if(f!=null){a(e,["thought"],f)}const p=s(t,["thoughtSignature"]);if(p!=null){a(e,["thoughtSignature"],p)}const h=s(t,["videoMetadata"]);if(h!=null){a(e,["videoMetadata"],h)}const m=s(t,["toolCall"]);if(m!=null){a(e,["toolCall"],m)}const _=s(t,["toolResponse"]);if(_!=null){a(e,["toolResponse"],_)}const A=s(t,["partMetadata"]);if(A!=null){a(e,["partMetadata"],A)}return e}function S_(t){const e={};const n=s(t,["mediaResolution"]);if(n!=null){a(e,["mediaResolution"],n)}const i=s(t,["codeExecutionResult"]);if(i!=null){a(e,["codeExecutionResult"],i)}const r=s(t,["executableCode"]);if(r!=null){a(e,["executableCode"],r)}const o=s(t,["fileData"]);if(o!=null){a(e,["fileData"],o)}const l=s(t,["functionCall"]);if(l!=null){a(e,["functionCall"],l)}const u=s(t,["functionResponse"]);if(u!=null){a(e,["functionResponse"],u)}const c=s(t,["inlineData"]);if(c!=null){a(e,["inlineData"],c)}const d=s(t,["text"]);if(d!=null){a(e,["text"],d)}const f=s(t,["thought"]);if(f!=null){a(e,["thought"],f)}const p=s(t,["thoughtSignature"]);if(p!=null){a(e,["thoughtSignature"],p)}const h=s(t,["videoMetadata"]);if(h!=null){a(e,["videoMetadata"],h)}if(s(t,["toolCall"])!==void 0){throw new Error("toolCall parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).")}if(s(t,["toolResponse"])!==void 0){throw new Error("toolResponse parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).")}if(s(t,["partMetadata"])!==void 0){throw new Error("partMetadata parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).")}return e}function I_(t){const e={};const n=s(t,["retrievalConfig"]);if(n!=null){a(e,["retrievalConfig"],n)}const i=s(t,["functionCallingConfig"]);if(i!=null){a(e,["functionCallingConfig"],d_(i))}const r=s(t,["includeServerSideToolInvocations"]);if(r!=null){a(e,["includeServerSideToolInvocations"],r)}return e}function w_(t){const e={};const n=s(t,["retrievalConfig"]);if(n!=null){a(e,["retrievalConfig"],n)}const i=s(t,["functionCallingConfig"]);if(i!=null){a(e,["functionCallingConfig"],i)}if(s(t,["includeServerSideToolInvocations"])!==void 0){throw new Error("includeServerSideToolInvocations parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).")}return e}function R_(t){const e={};if(s(t,["retrieval"])!==void 0){throw new Error("retrieval parameter is not supported in Gemini API.")}const n=s(t,["computerUse"]);if(n!=null){a(e,["computerUse"],n)}const i=s(t,["fileSearch"]);if(i!=null){a(e,["fileSearch"],i)}const r=s(t,["googleSearch"]);if(r!=null){a(e,["googleSearch"],m_(r))}const o=s(t,["googleMaps"]);if(o!=null){a(e,["googleMaps"],g_(o))}const l=s(t,["codeExecution"]);if(l!=null){a(e,["codeExecution"],l)}if(s(t,["enterpriseWebSearch"])!==void 0){throw new Error("enterpriseWebSearch parameter is not supported in Gemini API.")}const u=s(t,["functionDeclarations"]);if(u!=null){let p=u;if(Array.isArray(p)){p=p.map(h=>{return h})}a(e,["functionDeclarations"],p)}const c=s(t,["googleSearchRetrieval"]);if(c!=null){a(e,["googleSearchRetrieval"],c)}if(s(t,["parallelAiSearch"])!==void 0){throw new Error("parallelAiSearch parameter is not supported in Gemini API.")}const d=s(t,["urlContext"]);if(d!=null){a(e,["urlContext"],d)}const f=s(t,["mcpServers"]);if(f!=null){let p=f;if(Array.isArray(p)){p=p.map(h=>{return h})}a(e,["mcpServers"],p)}return e}function P_(t){const e={};const n=s(t,["retrieval"]);if(n!=null){a(e,["retrieval"],n)}const i=s(t,["computerUse"]);if(i!=null){a(e,["computerUse"],i)}if(s(t,["fileSearch"])!==void 0){throw new Error("fileSearch parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).")}const r=s(t,["googleSearch"]);if(r!=null){a(e,["googleSearch"],r)}const o=s(t,["googleMaps"]);if(o!=null){a(e,["googleMaps"],o)}const l=s(t,["codeExecution"]);if(l!=null){a(e,["codeExecution"],l)}const u=s(t,["enterpriseWebSearch"]);if(u!=null){a(e,["enterpriseWebSearch"],u)}const c=s(t,["functionDeclarations"]);if(c!=null){let h=c;if(Array.isArray(h)){h=h.map(m=>{return f_(m)})}a(e,["functionDeclarations"],h)}const d=s(t,["googleSearchRetrieval"]);if(d!=null){a(e,["googleSearchRetrieval"],d)}const f=s(t,["parallelAiSearch"]);if(f!=null){a(e,["parallelAiSearch"],f)}const p=s(t,["urlContext"]);if(p!=null){a(e,["urlContext"],p)}if(s(t,["mcpServers"])!==void 0){throw new Error("mcpServers parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).")}return e}function N_(t,e){const n={};const i=s(t,["ttl"]);if(e!==void 0&&i!=null){a(e,["ttl"],i)}const r=s(t,["expireTime"]);if(e!==void 0&&r!=null){a(e,["expireTime"],r)}return n}function M_(t,e){const n={};const i=s(t,["ttl"]);if(e!==void 0&&i!=null){a(e,["ttl"],i)}const r=s(t,["expireTime"]);if(e!==void 0&&r!=null){a(e,["expireTime"],r)}return n}function k_(t,e){const n={};const i=s(e,["name"]);if(i!=null){a(n,["_url","name"],lt(t,i))}const r=s(e,["config"]);if(r!=null){N_(r,n)}return n}function x_(t,e){const n={};const i=s(e,["name"]);if(i!=null){a(n,["_url","name"],lt(t,i))}const r=s(e,["config"]);if(r!=null){M_(r,n)}return n}var ea=class extends We{constructor(e){super();this.apiClient=e;this.list=async(n={})=>{return new at(st.PAGED_ITEM_CACHED_CONTENTS,i=>this.listInternal(i),await this.listInternal(n),n)}}async create(e){var n,i,r,o;let l;let u="";let c={};if(this.apiClient.isVertexAI()){const d=r_(this.apiClient,e);u=H("cachedContents",d["_url"]);c=d["_query"];delete d["_url"];delete d["_query"];l=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>{return f.json()});return l.then(f=>{return f})}else{const d=i_(this.apiClient,e);u=H("cachedContents",d["_url"]);c=d["_query"];delete d["_url"];delete d["_query"];l=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(r=e.config)===null||r===void 0?void 0:r.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>{return f.json()});return l.then(f=>{return f})}}async get(e){var n,i,r,o;let l;let u="";let c={};if(this.apiClient.isVertexAI()){const d=h_(this.apiClient,e);u=H("{name}",d["_url"]);c=d["_query"];delete d["_url"];delete d["_query"];l=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>{return f.json()});return l.then(f=>{return f})}else{const d=p_(this.apiClient,e);u=H("{name}",d["_url"]);c=d["_query"];delete d["_url"];delete d["_query"];l=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(r=e.config)===null||r===void 0?void 0:r.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>{return f.json()});return l.then(f=>{return f})}}async delete(e){var n,i,r,o;let l;let u="";let c={};if(this.apiClient.isVertexAI()){const d=s_(this.apiClient,e);u=H("{name}",d["_url"]);c=d["_query"];delete d["_url"];delete d["_query"];l=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"DELETE",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>{return f.json().then(p=>{const h=p;h.sdkHttpResponse={headers:f.headers};return h})});return l.then(f=>{const p=l_(f);const h=new Wi;Object.assign(h,p);return h})}else{const d=o_(this.apiClient,e);u=H("{name}",d["_url"]);c=d["_query"];delete d["_url"];delete d["_query"];l=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"DELETE",httpOptions:(r=e.config)===null||r===void 0?void 0:r.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>{return f.json().then(p=>{const h=p;h.sdkHttpResponse={headers:f.headers};return h})});return l.then(f=>{const p=a_(f);const h=new Wi;Object.assign(h,p);return h})}}async update(e){var n,i,r,o;let l;let u="";let c={};if(this.apiClient.isVertexAI()){const d=x_(this.apiClient,e);u=H("{name}",d["_url"]);c=d["_query"];delete d["_url"];delete d["_query"];l=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"PATCH",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>{return f.json()});return l.then(f=>{return f})}else{const d=k_(this.apiClient,e);u=H("{name}",d["_url"]);c=d["_query"];delete d["_url"];delete d["_query"];l=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"PATCH",httpOptions:(r=e.config)===null||r===void 0?void 0:r.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>{return f.json()});return l.then(f=>{return f})}}async listInternal(e){var n,i,r,o;let l;let u="";let c={};if(this.apiClient.isVertexAI()){const d=T_(e);u=H("cachedContents",d["_url"]);c=d["_query"];delete d["_url"];delete d["_query"];l=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>{return f.json().then(p=>{const h=p;h.sdkHttpResponse={headers:f.headers};return h})});return l.then(f=>{const p=C_(f);const h=new Yi;Object.assign(h,p);return h})}else{const d=__(e);u=H("cachedContents",d["_url"]);c=d["_query"];delete d["_url"];delete d["_query"];l=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(r=e.config)===null||r===void 0?void 0:r.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>{return f.json().then(p=>{const h=p;h.sdkHttpResponse={headers:f.headers};return h})});return l.then(f=>{const p=A_(f);const h=new Yi;Object.assign(h,p);return h})}}};function mt(t,e){var n={};for(var i in t)if(Object.prototype.hasOwnProperty.call(t,i)&&e.indexOf(i)<0)n[i]=t[i];if(t!=null&&typeof Object.getOwnPropertySymbols==="function")for(var r=0,i=Object.getOwnPropertySymbols(t);r<i.length;r++){if(e.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(t,i[r]))n[i[r]]=t[i[r]]}return n}function $d(t){var e=typeof Symbol==="function"&&Symbol.iterator,n=e&&t[e],i=0;if(n)return n.call(t);if(t&&typeof t.length==="number")return{next:function(){if(t&&i>=t.length)t=void 0;return{value:t&&t[i++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function X(t){return this instanceof X?(this.v=t,this):new X(t)}function Je(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=n.apply(t,e||[]),r,o=[];return r=Object.create((typeof AsyncIterator==="function"?AsyncIterator:Object).prototype),u("next"),u("throw"),u("return",l),r[Symbol.asyncIterator]=function(){return this},r;function l(m){return function(_){return Promise.resolve(_).then(m,p)}}function u(m,_){if(i[m]){r[m]=function(A){return new Promise(function(T,v){o.push([m,A,T,v])>1||c(m,A)})};if(_)r[m]=_(r[m])}}function c(m,_){try{d(i[m](_))}catch(A){h(o[0][3],A)}}function d(m){m.value instanceof X?Promise.resolve(m.value.v).then(f,p):h(o[0][2],m)}function f(m){c("next",m)}function p(m){c("throw",m)}function h(m,_){if(m(_),o.shift(),o.length)c(o[0][0],o[0][1])}}function Ke(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],n;return e?e.call(t):(t=typeof $d==="function"?$d(t):t[Symbol.iterator](),n={},i("next"),i("throw"),i("return"),n[Symbol.asyncIterator]=function(){return this},n);function i(o){n[o]=t[o]&&function(l){return new Promise(function(u,c){l=t[o](l),r(u,c,l.done,l.value)})}}function r(o,l,u,c){Promise.resolve(c).then(function(d){o({value:d,done:u})},l)}}function D_(t){var e;if(t.candidates==void 0||t.candidates.length===0){return false}const n=(e=t.candidates[0])===null||e===void 0?void 0:e.content;if(n===void 0){return false}return Nf(n)}function Nf(t){if(t.parts===void 0||t.parts.length===0){return false}for(const e of t.parts){if(e===void 0||Object.keys(e).length===0){return false}}return true}function U_(t){if(t.length===0){return}for(const e of t){if(e.role!=="user"&&e.role!=="model"){throw new Error(`Role must be user or model, but got ${e.role}.`)}}}function Jd(t){if(t===void 0||t.length===0){return[]}const e=[];const n=t.length;let i=0;while(i<n){if(t[i].role==="user"){e.push(t[i]);i++}else{const r=[];let o=true;while(i<n&&t[i].role==="model"){r.push(t[i]);if(o&&!Nf(t[i])){o=false}i++}if(o){e.push(...r)}else{e.pop()}}}return e}var ta=class{constructor(e,n){this.modelsModule=e;this.apiClient=n}create(e){return new na(this.apiClient,this.modelsModule,e.model,e.config,structuredClone(e.history))}};var na=class{constructor(e,n,i,r={},o=[]){this.apiClient=e;this.modelsModule=n;this.model=i;this.config=r;this.history=o;this.sendPromise=Promise.resolve();U_(o)}async sendMessage(e){var n;await this.sendPromise;const i=he(e.message);const r=this.modelsModule.generateContent({model:this.model,contents:this.getHistory(true).concat(i),config:(n=e.config)!==null&&n!==void 0?n:this.config});this.sendPromise=(async()=>{var o,l,u;const c=await r;const d=(l=(o=c.candidates)===null||o===void 0?void 0:o[0])===null||l===void 0?void 0:l.content;const f=c.automaticFunctionCallingHistory;const p=this.getHistory(true).length;let h=[];if(f!=null){h=(u=f.slice(p))!==null&&u!==void 0?u:[]}const m=d?[d]:[];this.recordHistory(i,m,h);return})();await this.sendPromise.catch(()=>{this.sendPromise=Promise.resolve()});return r}async sendMessageStream(e){var n;await this.sendPromise;const i=he(e.message);const r=this.modelsModule.generateContentStream({model:this.model,contents:this.getHistory(true).concat(i),config:(n=e.config)!==null&&n!==void 0?n:this.config});this.sendPromise=r.then(()=>void 0).catch(()=>void 0);const o=await r;const l=this.processStreamResponse(o,i);return l}getHistory(e=false){const n=e?Jd(this.history):this.history;return structuredClone(n)}processStreamResponse(e,n){return Je(this,arguments,function*i(){var r,o,l,u;var c,d;const f=[];try{for(var p=true,h=Ke(e),m;m=yield X(h.next()),r=m.done,!r;p=true){u=m.value;p=false;const _=u;if(D_(_)){const A=(d=(c=_.candidates)===null||c===void 0?void 0:c[0])===null||d===void 0?void 0:d.content;if(A!==void 0){f.push(A)}}yield yield X(_)}}catch(_){o={error:_}}finally{try{if(!p&&!r&&(l=h.return))yield X(l.call(h))}finally{if(o)throw o.error}}this.recordHistory(n,f)})}recordHistory(e,n,i){let r=[];if(n.length>0&&n.every(o=>o.role!==void 0)){r=n}else{r.push({role:"model",parts:[]})}if(i&&i.length>0){this.history.push(...Jd(i))}else{this.history.push(e)}this.history.push(...r)}};var Zi=class t extends Error{constructor(e){super(e.message);this.name="ApiError";this.status=e.status;Object.setPrototypeOf(this,t.prototype)}};function L_(t){const e={};const n=s(t,["file"]);if(n!=null){a(e,["file"],n)}return e}function G_(t){const e={};const n=s(t,["sdkHttpResponse"]);if(n!=null){a(e,["sdkHttpResponse"],n)}return e}function O_(t){const e={};const n=s(t,["name"]);if(n!=null){a(e,["_url","file"],Fa(n))}return e}function b_(t){const e={};const n=s(t,["sdkHttpResponse"]);if(n!=null){a(e,["sdkHttpResponse"],n)}return e}function F_(t){const e={};const n=s(t,["name"]);if(n!=null){a(e,["_url","file"],Fa(n))}return e}function q_(t){const e={};const n=s(t,["uris"]);if(n!=null){a(e,["uris"],n)}return e}function H_(t,e){const n={};const i=s(t,["pageSize"]);if(e!==void 0&&i!=null){a(e,["_query","pageSize"],i)}const r=s(t,["pageToken"]);if(e!==void 0&&r!=null){a(e,["_query","pageToken"],r)}return n}function V_(t){const e={};const n=s(t,["config"]);if(n!=null){H_(n,e)}return e}function B_(t){const e={};const n=s(t,["sdkHttpResponse"]);if(n!=null){a(e,["sdkHttpResponse"],n)}const i=s(t,["nextPageToken"]);if(i!=null){a(e,["nextPageToken"],i)}const r=s(t,["files"]);if(r!=null){let o=r;if(Array.isArray(o)){o=o.map(l=>{return l})}a(e,["files"],o)}return e}function $_(t){const e={};const n=s(t,["sdkHttpResponse"]);if(n!=null){a(e,["sdkHttpResponse"],n)}const i=s(t,["files"]);if(i!=null){let r=i;if(Array.isArray(r)){r=r.map(o=>{return o})}a(e,["files"],r)}return e}var ia=class extends We{constructor(e){super();this.apiClient=e;this.list=async(n={})=>{return new at(st.PAGED_ITEM_FILES,i=>this.listInternal(i),await this.listInternal(n),n)}}async upload(e){if(this.apiClient.isVertexAI()){throw new Error("Gemini Enterprise Agent Platform (previously known as Vertex AI) does not support uploading files. You can share files through a GCS bucket.")}return this.apiClient.uploadFile(e.file,e.config).then(n=>{return n})}async download(e){await this.apiClient.downloadFile(e)}async registerFiles(e){throw new Error("registerFiles is only supported in Node.js environments.")}async _registerFiles(e){return this.registerFilesInternal(e)}async listInternal(e){var n,i;let r;let o="";let l={};if(this.apiClient.isVertexAI()){throw new Error("This method is only supported by the Gemini Developer API.")}else{const u=V_(e);o=H("files",u["_url"]);l=u["_query"];delete u["_url"];delete u["_query"];r=this.apiClient.request({path:o,queryParams:l,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(c=>{return c.json().then(d=>{const f=d;f.sdkHttpResponse={headers:c.headers};return f})});return r.then(c=>{const d=B_(c);const f=new Js;Object.assign(f,d);return f})}}async createInternal(e){var n,i;let r;let o="";let l={};if(this.apiClient.isVertexAI()){throw new Error("This method is only supported by the Gemini Developer API.")}else{const u=L_(e);o=H("upload/v1beta/files",u["_url"]);l=u["_query"];delete u["_url"];delete u["_query"];r=this.apiClient.request({path:o,queryParams:l,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(c=>{return c.json()});return r.then(c=>{const d=G_(c);const f=new Ks;Object.assign(f,d);return f})}}async get(e){var n,i;let r;let o="";let l={};if(this.apiClient.isVertexAI()){throw new Error("This method is only supported by the Gemini Developer API.")}else{const u=F_(e);o=H("files/{file}",u["_url"]);l=u["_query"];delete u["_url"];delete u["_query"];r=this.apiClient.request({path:o,queryParams:l,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(c=>{return c.json()});return r.then(c=>{return c})}}async delete(e){var n,i;let r;let o="";let l={};if(this.apiClient.isVertexAI()){throw new Error("This method is only supported by the Gemini Developer API.")}else{const u=O_(e);o=H("files/{file}",u["_url"]);l=u["_query"];delete u["_url"];delete u["_query"];r=this.apiClient.request({path:o,queryParams:l,body:JSON.stringify(u),httpMethod:"DELETE",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(c=>{return c.json().then(d=>{const f=d;f.sdkHttpResponse={headers:c.headers};return f})});return r.then(c=>{const d=b_(c);const f=new Ws;Object.assign(f,d);return f})}}async registerFilesInternal(e){var n,i;let r;let o="";let l={};if(this.apiClient.isVertexAI()){throw new Error("This method is only supported by the Gemini Developer API.")}else{const u=q_(e);o=H("files:register",u["_url"]);l=u["_query"];delete u["_url"];delete u["_query"];r=this.apiClient.request({path:o,queryParams:l,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(c=>{return c.json()});return r.then(c=>{const d=$_(c);const f=new Ys;Object.assign(f,d);return f})}}};function Kd(t){const e={};if(s(t,["languageCodes"])!==void 0){throw new Error("languageCodes parameter is not supported in Gemini API.")}return e}function J_(t){const e={};const n=s(t,["apiKey"]);if(n!=null){a(e,["apiKey"],n)}if(s(t,["apiKeyConfig"])!==void 0){throw new Error("apiKeyConfig parameter is not supported in Gemini API.")}if(s(t,["authType"])!==void 0){throw new Error("authType parameter is not supported in Gemini API.")}if(s(t,["googleServiceAccountConfig"])!==void 0){throw new Error("googleServiceAccountConfig parameter is not supported in Gemini API.")}if(s(t,["httpBasicAuthConfig"])!==void 0){throw new Error("httpBasicAuthConfig parameter is not supported in Gemini API.")}if(s(t,["oauthConfig"])!==void 0){throw new Error("oauthConfig parameter is not supported in Gemini API.")}if(s(t,["oidcConfig"])!==void 0){throw new Error("oidcConfig parameter is not supported in Gemini API.")}return e}function Oi(t){const e={};const n=s(t,["data"]);if(n!=null){a(e,["data"],n)}if(s(t,["displayName"])!==void 0){throw new Error("displayName parameter is not supported in Gemini API.")}const i=s(t,["mimeType"]);if(i!=null){a(e,["mimeType"],i)}return e}function K_(t){const e={};const n=s(t,["parts"]);if(n!=null){let r=n;if(Array.isArray(r)){r=r.map(o=>{return uT(o)})}a(e,["parts"],r)}const i=s(t,["role"]);if(i!=null){a(e,["role"],i)}return e}function W_(t){const e={};const n=s(t,["parts"]);if(n!=null){let r=n;if(Array.isArray(r)){r=r.map(o=>{return cT(o)})}a(e,["parts"],r)}const i=s(t,["role"]);if(i!=null){a(e,["role"],i)}return e}function Y_(t){const e={};if(s(t,["displayName"])!==void 0){throw new Error("displayName parameter is not supported in Gemini API.")}const n=s(t,["fileUri"]);if(n!=null){a(e,["fileUri"],n)}const i=s(t,["mimeType"]);if(i!=null){a(e,["mimeType"],i)}return e}function z_(t){const e={};const n=s(t,["id"]);if(n!=null){a(e,["id"],n)}const i=s(t,["args"]);if(i!=null){a(e,["args"],i)}const r=s(t,["name"]);if(r!=null){a(e,["name"],r)}if(s(t,["partialArgs"])!==void 0){throw new Error("partialArgs parameter is not supported in Gemini API.")}if(s(t,["willContinue"])!==void 0){throw new Error("willContinue parameter is not supported in Gemini API.")}return e}function X_(t){const e={};const n=s(t,["description"]);if(n!=null){a(e,["description"],n)}const i=s(t,["name"]);if(i!=null){a(e,["name"],i)}const r=s(t,["parameters"]);if(r!=null){a(e,["parameters"],r)}const o=s(t,["parametersJsonSchema"]);if(o!=null){a(e,["parametersJsonSchema"],o)}const l=s(t,["response"]);if(l!=null){a(e,["response"],l)}const u=s(t,["responseJsonSchema"]);if(u!=null){a(e,["responseJsonSchema"],u)}if(s(t,["behavior"])!==void 0){throw new Error("behavior parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).")}return e}function Q_(t){const e={};const n=s(t,["modelSelectionConfig"]);if(n!=null){a(e,["modelConfig"],n)}const i=s(t,["responseJsonSchema"]);if(i!=null){a(e,["responseJsonSchema"],i)}const r=s(t,["audioTimestamp"]);if(r!=null){a(e,["audioTimestamp"],r)}const o=s(t,["candidateCount"]);if(o!=null){a(e,["candidateCount"],o)}const l=s(t,["enableAffectiveDialog"]);if(l!=null){a(e,["enableAffectiveDialog"],l)}const u=s(t,["frequencyPenalty"]);if(u!=null){a(e,["frequencyPenalty"],u)}const c=s(t,["logprobs"]);if(c!=null){a(e,["logprobs"],c)}const d=s(t,["maxOutputTokens"]);if(d!=null){a(e,["maxOutputTokens"],d)}const f=s(t,["mediaResolution"]);if(f!=null){a(e,["mediaResolution"],f)}const p=s(t,["presencePenalty"]);if(p!=null){a(e,["presencePenalty"],p)}const h=s(t,["responseLogprobs"]);if(h!=null){a(e,["responseLogprobs"],h)}const m=s(t,["responseMimeType"]);if(m!=null){a(e,["responseMimeType"],m)}const _=s(t,["responseModalities"]);if(_!=null){a(e,["responseModalities"],_)}const A=s(t,["responseSchema"]);if(A!=null){a(e,["responseSchema"],A)}const T=s(t,["routingConfig"]);if(T!=null){a(e,["routingConfig"],T)}const v=s(t,["seed"]);if(v!=null){a(e,["seed"],v)}const G=s(t,["speechConfig"]);if(G!=null){a(e,["speechConfig"],G)}const D=s(t,["stopSequences"]);if(D!=null){a(e,["stopSequences"],D)}const O=s(t,["temperature"]);if(O!=null){a(e,["temperature"],O)}const L=s(t,["thinkingConfig"]);if(L!=null){a(e,["thinkingConfig"],L)}const R=s(t,["topK"]);if(R!=null){a(e,["topK"],R)}const q=s(t,["topP"]);if(q!=null){a(e,["topP"],q)}if(s(t,["enableEnhancedCivicAnswers"])!==void 0){throw new Error("enableEnhancedCivicAnswers parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).")}return e}function Z_(t){const e={};const n=s(t,["authConfig"]);if(n!=null){a(e,["authConfig"],J_(n))}const i=s(t,["enableWidget"]);if(i!=null){a(e,["enableWidget"],i)}return e}function j_(t){const e={};const n=s(t,["searchTypes"]);if(n!=null){a(e,["searchTypes"],n)}if(s(t,["blockingConfidence"])!==void 0){throw new Error("blockingConfidence parameter is not supported in Gemini API.")}if(s(t,["excludeDomains"])!==void 0){throw new Error("excludeDomains parameter is not supported in Gemini API.")}const i=s(t,["timeRangeFilter"]);if(i!=null){a(e,["timeRangeFilter"],i)}return e}function eT(t,e){const n={};const i=s(t,["generationConfig"]);if(e!==void 0&&i!=null){a(e,["setup","generationConfig"],i)}const r=s(t,["responseModalities"]);if(e!==void 0&&r!=null){a(e,["setup","generationConfig","responseModalities"],r)}const o=s(t,["temperature"]);if(e!==void 0&&o!=null){a(e,["setup","generationConfig","temperature"],o)}const l=s(t,["topP"]);if(e!==void 0&&l!=null){a(e,["setup","generationConfig","topP"],l)}const u=s(t,["topK"]);if(e!==void 0&&u!=null){a(e,["setup","generationConfig","topK"],u)}const c=s(t,["maxOutputTokens"]);if(e!==void 0&&c!=null){a(e,["setup","generationConfig","maxOutputTokens"],c)}const d=s(t,["mediaResolution"]);if(e!==void 0&&d!=null){a(e,["setup","generationConfig","mediaResolution"],d)}const f=s(t,["seed"]);if(e!==void 0&&f!=null){a(e,["setup","generationConfig","seed"],f)}const p=s(t,["speechConfig"]);if(e!==void 0&&p!=null){a(e,["setup","generationConfig","speechConfig"],ba(p))}const h=s(t,["thinkingConfig"]);if(e!==void 0&&h!=null){a(e,["setup","generationConfig","thinkingConfig"],h)}const m=s(t,["enableAffectiveDialog"]);if(e!==void 0&&m!=null){a(e,["setup","generationConfig","enableAffectiveDialog"],m)}const _=s(t,["systemInstruction"]);if(e!==void 0&&_!=null){a(e,["setup","systemInstruction"],K_(he(_)))}const A=s(t,["tools"]);if(e!==void 0&&A!=null){let V=nn(A);if(Array.isArray(V)){V=V.map(k=>{return pT(tn(k))})}a(e,["setup","tools"],V)}const T=s(t,["sessionResumption"]);if(e!==void 0&&T!=null){a(e,["setup","sessionResumption"],fT(T))}const v=s(t,["inputAudioTranscription"]);if(e!==void 0&&v!=null){a(e,["setup","inputAudioTranscription"],Kd(v))}const G=s(t,["outputAudioTranscription"]);if(e!==void 0&&G!=null){a(e,["setup","outputAudioTranscription"],Kd(G))}const D=s(t,["realtimeInputConfig"]);if(e!==void 0&&D!=null){a(e,["setup","realtimeInputConfig"],D)}const O=s(t,["contextWindowCompression"]);if(e!==void 0&&O!=null){a(e,["setup","contextWindowCompression"],O)}const L=s(t,["proactivity"]);if(e!==void 0&&L!=null){a(e,["setup","proactivity"],L)}if(s(t,["explicitVadSignal"])!==void 0){throw new Error("explicitVadSignal parameter is not supported in Gemini API.")}const R=s(t,["avatarConfig"]);if(e!==void 0&&R!=null){a(e,["setup","avatarConfig"],R)}const q=s(t,["safetySettings"]);if(e!==void 0&&q!=null){let V=q;if(Array.isArray(V)){V=V.map(k=>{return dT(k)})}a(e,["setup","safetySettings"],V)}return n}function tT(t,e){const n={};const i=s(t,["generationConfig"]);if(e!==void 0&&i!=null){a(e,["setup","generationConfig"],Q_(i))}const r=s(t,["responseModalities"]);if(e!==void 0&&r!=null){a(e,["setup","generationConfig","responseModalities"],r)}const o=s(t,["temperature"]);if(e!==void 0&&o!=null){a(e,["setup","generationConfig","temperature"],o)}const l=s(t,["topP"]);if(e!==void 0&&l!=null){a(e,["setup","generationConfig","topP"],l)}const u=s(t,["topK"]);if(e!==void 0&&u!=null){a(e,["setup","generationConfig","topK"],u)}const c=s(t,["maxOutputTokens"]);if(e!==void 0&&c!=null){a(e,["setup","generationConfig","maxOutputTokens"],c)}const d=s(t,["mediaResolution"]);if(e!==void 0&&d!=null){a(e,["setup","generationConfig","mediaResolution"],d)}const f=s(t,["seed"]);if(e!==void 0&&f!=null){a(e,["setup","generationConfig","seed"],f)}const p=s(t,["speechConfig"]);if(e!==void 0&&p!=null){a(e,["setup","generationConfig","speechConfig"],ba(p))}const h=s(t,["thinkingConfig"]);if(e!==void 0&&h!=null){a(e,["setup","generationConfig","thinkingConfig"],h)}const m=s(t,["enableAffectiveDialog"]);if(e!==void 0&&m!=null){a(e,["setup","generationConfig","enableAffectiveDialog"],m)}const _=s(t,["systemInstruction"]);if(e!==void 0&&_!=null){a(e,["setup","systemInstruction"],W_(he(_)))}const A=s(t,["tools"]);if(e!==void 0&&A!=null){let k=nn(A);if(Array.isArray(k)){k=k.map($=>{return hT(tn($))})}a(e,["setup","tools"],k)}const T=s(t,["sessionResumption"]);if(e!==void 0&&T!=null){a(e,["setup","sessionResumption"],T)}const v=s(t,["inputAudioTranscription"]);if(e!==void 0&&v!=null){a(e,["setup","inputAudioTranscription"],v)}const G=s(t,["outputAudioTranscription"]);if(e!==void 0&&G!=null){a(e,["setup","outputAudioTranscription"],G)}const D=s(t,["realtimeInputConfig"]);if(e!==void 0&&D!=null){a(e,["setup","realtimeInputConfig"],D)}const O=s(t,["contextWindowCompression"]);if(e!==void 0&&O!=null){a(e,["setup","contextWindowCompression"],O)}const L=s(t,["proactivity"]);if(e!==void 0&&L!=null){a(e,["setup","proactivity"],L)}const R=s(t,["explicitVadSignal"]);if(e!==void 0&&R!=null){a(e,["setup","explicitVadSignal"],R)}const q=s(t,["avatarConfig"]);if(e!==void 0&&q!=null){a(e,["setup","avatarConfig"],q)}const V=s(t,["safetySettings"]);if(e!==void 0&&V!=null){let k=V;if(Array.isArray(k)){k=k.map($=>{return $})}a(e,["setup","safetySettings"],k)}return n}function nT(t,e){const n={};const i=s(e,["model"]);if(i!=null){a(n,["setup","model"],j(t,i))}const r=s(e,["config"]);if(r!=null){a(n,["config"],eT(r,n))}return n}function iT(t,e){const n={};const i=s(e,["model"]);if(i!=null){a(n,["setup","model"],j(t,i))}const r=s(e,["config"]);if(r!=null){a(n,["config"],tT(r,n))}return n}function rT(t){const e={};const n=s(t,["musicGenerationConfig"]);if(n!=null){a(e,["musicGenerationConfig"],n)}return e}function oT(t){const e={};const n=s(t,["weightedPrompts"]);if(n!=null){let i=n;if(Array.isArray(i)){i=i.map(r=>{return r})}a(e,["weightedPrompts"],i)}return e}function sT(t){const e={};const n=s(t,["media"]);if(n!=null){let d=mf(n);if(Array.isArray(d)){d=d.map(f=>{return Oi(f)})}a(e,["mediaChunks"],d)}const i=s(t,["audio"]);if(i!=null){a(e,["audio"],Oi(Ef(i)))}const r=s(t,["audioStreamEnd"]);if(r!=null){a(e,["audioStreamEnd"],r)}const o=s(t,["video"]);if(o!=null){a(e,["video"],Oi(yf(o)))}const l=s(t,["text"]);if(l!=null){a(e,["text"],l)}const u=s(t,["activityStart"]);if(u!=null){a(e,["activityStart"],u)}const c=s(t,["activityEnd"]);if(c!=null){a(e,["activityEnd"],c)}return e}function aT(t){const e={};const n=s(t,["media"]);if(n!=null){let d=mf(n);if(Array.isArray(d)){d=d.map(f=>{return f})}a(e,["mediaChunks"],d)}const i=s(t,["audio"]);if(i!=null){a(e,["audio"],Ef(i))}const r=s(t,["audioStreamEnd"]);if(r!=null){a(e,["audioStreamEnd"],r)}const o=s(t,["video"]);if(o!=null){a(e,["video"],yf(o))}const l=s(t,["text"]);if(l!=null){a(e,["text"],l)}const u=s(t,["activityStart"]);if(u!=null){a(e,["activityStart"],u)}const c=s(t,["activityEnd"]);if(c!=null){a(e,["activityEnd"],c)}return e}function lT(t){const e={};const n=s(t,["setupComplete"]);if(n!=null){a(e,["setupComplete"],n)}const i=s(t,["serverContent"]);if(i!=null){a(e,["serverContent"],i)}const r=s(t,["toolCall"]);if(r!=null){a(e,["toolCall"],r)}const o=s(t,["toolCallCancellation"]);if(o!=null){a(e,["toolCallCancellation"],o)}const l=s(t,["usageMetadata"]);if(l!=null){a(e,["usageMetadata"],gT(l))}const u=s(t,["goAway"]);if(u!=null){a(e,["goAway"],u)}const c=s(t,["sessionResumptionUpdate"]);if(c!=null){a(e,["sessionResumptionUpdate"],c)}const d=s(t,["voiceActivityDetectionSignal"]);if(d!=null){a(e,["voiceActivityDetectionSignal"],d)}const f=s(t,["voiceActivity"]);if(f!=null){a(e,["voiceActivity"],mT(f))}return e}function uT(t){const e={};const n=s(t,["mediaResolution"]);if(n!=null){a(e,["mediaResolution"],n)}const i=s(t,["codeExecutionResult"]);if(i!=null){a(e,["codeExecutionResult"],i)}const r=s(t,["executableCode"]);if(r!=null){a(e,["executableCode"],r)}const o=s(t,["fileData"]);if(o!=null){a(e,["fileData"],Y_(o))}const l=s(t,["functionCall"]);if(l!=null){a(e,["functionCall"],z_(l))}const u=s(t,["functionResponse"]);if(u!=null){a(e,["functionResponse"],u)}const c=s(t,["inlineData"]);if(c!=null){a(e,["inlineData"],Oi(c))}const d=s(t,["text"]);if(d!=null){a(e,["text"],d)}const f=s(t,["thought"]);if(f!=null){a(e,["thought"],f)}const p=s(t,["thoughtSignature"]);if(p!=null){a(e,["thoughtSignature"],p)}const h=s(t,["videoMetadata"]);if(h!=null){a(e,["videoMetadata"],h)}const m=s(t,["toolCall"]);if(m!=null){a(e,["toolCall"],m)}const _=s(t,["toolResponse"]);if(_!=null){a(e,["toolResponse"],_)}const A=s(t,["partMetadata"]);if(A!=null){a(e,["partMetadata"],A)}return e}function cT(t){const e={};const n=s(t,["mediaResolution"]);if(n!=null){a(e,["mediaResolution"],n)}const i=s(t,["codeExecutionResult"]);if(i!=null){a(e,["codeExecutionResult"],i)}const r=s(t,["executableCode"]);if(r!=null){a(e,["executableCode"],r)}const o=s(t,["fileData"]);if(o!=null){a(e,["fileData"],o)}const l=s(t,["functionCall"]);if(l!=null){a(e,["functionCall"],l)}const u=s(t,["functionResponse"]);if(u!=null){a(e,["functionResponse"],u)}const c=s(t,["inlineData"]);if(c!=null){a(e,["inlineData"],c)}const d=s(t,["text"]);if(d!=null){a(e,["text"],d)}const f=s(t,["thought"]);if(f!=null){a(e,["thought"],f)}const p=s(t,["thoughtSignature"]);if(p!=null){a(e,["thoughtSignature"],p)}const h=s(t,["videoMetadata"]);if(h!=null){a(e,["videoMetadata"],h)}if(s(t,["toolCall"])!==void 0){throw new Error("toolCall parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).")}if(s(t,["toolResponse"])!==void 0){throw new Error("toolResponse parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).")}if(s(t,["partMetadata"])!==void 0){throw new Error("partMetadata parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).")}return e}function dT(t){const e={};const n=s(t,["category"]);if(n!=null){a(e,["category"],n)}if(s(t,["method"])!==void 0){throw new Error("method parameter is not supported in Gemini API.")}const i=s(t,["threshold"]);if(i!=null){a(e,["threshold"],i)}return e}function fT(t){const e={};const n=s(t,["handle"]);if(n!=null){a(e,["handle"],n)}if(s(t,["transparent"])!==void 0){throw new Error("transparent parameter is not supported in Gemini API.")}return e}function pT(t){const e={};if(s(t,["retrieval"])!==void 0){throw new Error("retrieval parameter is not supported in Gemini API.")}const n=s(t,["computerUse"]);if(n!=null){a(e,["computerUse"],n)}const i=s(t,["fileSearch"]);if(i!=null){a(e,["fileSearch"],i)}const r=s(t,["googleSearch"]);if(r!=null){a(e,["googleSearch"],j_(r))}const o=s(t,["googleMaps"]);if(o!=null){a(e,["googleMaps"],Z_(o))}const l=s(t,["codeExecution"]);if(l!=null){a(e,["codeExecution"],l)}if(s(t,["enterpriseWebSearch"])!==void 0){throw new Error("enterpriseWebSearch parameter is not supported in Gemini API.")}const u=s(t,["functionDeclarations"]);if(u!=null){let p=u;if(Array.isArray(p)){p=p.map(h=>{return h})}a(e,["functionDeclarations"],p)}const c=s(t,["googleSearchRetrieval"]);if(c!=null){a(e,["googleSearchRetrieval"],c)}if(s(t,["parallelAiSearch"])!==void 0){throw new Error("parallelAiSearch parameter is not supported in Gemini API.")}const d=s(t,["urlContext"]);if(d!=null){a(e,["urlContext"],d)}const f=s(t,["mcpServers"]);if(f!=null){let p=f;if(Array.isArray(p)){p=p.map(h=>{return h})}a(e,["mcpServers"],p)}return e}function hT(t){const e={};const n=s(t,["retrieval"]);if(n!=null){a(e,["retrieval"],n)}const i=s(t,["computerUse"]);if(i!=null){a(e,["computerUse"],i)}if(s(t,["fileSearch"])!==void 0){throw new Error("fileSearch parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).")}const r=s(t,["googleSearch"]);if(r!=null){a(e,["googleSearch"],r)}const o=s(t,["googleMaps"]);if(o!=null){a(e,["googleMaps"],o)}const l=s(t,["codeExecution"]);if(l!=null){a(e,["codeExecution"],l)}const u=s(t,["enterpriseWebSearch"]);if(u!=null){a(e,["enterpriseWebSearch"],u)}const c=s(t,["functionDeclarations"]);if(c!=null){let h=c;if(Array.isArray(h)){h=h.map(m=>{return X_(m)})}a(e,["functionDeclarations"],h)}const d=s(t,["googleSearchRetrieval"]);if(d!=null){a(e,["googleSearchRetrieval"],d)}const f=s(t,["parallelAiSearch"]);if(f!=null){a(e,["parallelAiSearch"],f)}const p=s(t,["urlContext"]);if(p!=null){a(e,["urlContext"],p)}if(s(t,["mcpServers"])!==void 0){throw new Error("mcpServers parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).")}return e}function gT(t){const e={};const n=s(t,["promptTokenCount"]);if(n!=null){a(e,["promptTokenCount"],n)}const i=s(t,["cachedContentTokenCount"]);if(i!=null){a(e,["cachedContentTokenCount"],i)}const r=s(t,["candidatesTokenCount"]);if(r!=null){a(e,["responseTokenCount"],r)}const o=s(t,["toolUsePromptTokenCount"]);if(o!=null){a(e,["toolUsePromptTokenCount"],o)}const l=s(t,["thoughtsTokenCount"]);if(l!=null){a(e,["thoughtsTokenCount"],l)}const u=s(t,["totalTokenCount"]);if(u!=null){a(e,["totalTokenCount"],u)}const c=s(t,["promptTokensDetails"]);if(c!=null){let m=c;if(Array.isArray(m)){m=m.map(_=>{return _})}a(e,["promptTokensDetails"],m)}const d=s(t,["cacheTokensDetails"]);if(d!=null){let m=d;if(Array.isArray(m)){m=m.map(_=>{return _})}a(e,["cacheTokensDetails"],m)}const f=s(t,["candidatesTokensDetails"]);if(f!=null){let m=f;if(Array.isArray(m)){m=m.map(_=>{return _})}a(e,["responseTokensDetails"],m)}const p=s(t,["toolUsePromptTokensDetails"]);if(p!=null){let m=p;if(Array.isArray(m)){m=m.map(_=>{return _})}a(e,["toolUsePromptTokensDetails"],m)}const h=s(t,["trafficType"]);if(h!=null){a(e,["trafficType"],h)}return e}function mT(t){const e={};const n=s(t,["type"]);if(n!=null){a(e,["voiceActivityType"],n)}return e}function yT(t,e){const n={};const i=s(t,["apiKey"]);if(i!=null){a(n,["apiKey"],i)}if(s(t,["apiKeyConfig"])!==void 0){throw new Error("apiKeyConfig parameter is not supported in Gemini API.")}if(s(t,["authType"])!==void 0){throw new Error("authType parameter is not supported in Gemini API.")}if(s(t,["googleServiceAccountConfig"])!==void 0){throw new Error("googleServiceAccountConfig parameter is not supported in Gemini API.")}if(s(t,["httpBasicAuthConfig"])!==void 0){throw new Error("httpBasicAuthConfig parameter is not supported in Gemini API.")}if(s(t,["oauthConfig"])!==void 0){throw new Error("oauthConfig parameter is not supported in Gemini API.")}if(s(t,["oidcConfig"])!==void 0){throw new Error("oidcConfig parameter is not supported in Gemini API.")}return n}function ET(t,e){const n={};const i=s(t,["data"]);if(i!=null){a(n,["data"],i)}if(s(t,["displayName"])!==void 0){throw new Error("displayName parameter is not supported in Gemini API.")}const r=s(t,["mimeType"]);if(r!=null){a(n,["mimeType"],r)}return n}function _T(t,e){const n={};const i=s(t,["content"]);if(i!=null){a(n,["content"],i)}const r=s(t,["citationMetadata"]);if(r!=null){a(n,["citationMetadata"],TT(r))}const o=s(t,["tokenCount"]);if(o!=null){a(n,["tokenCount"],o)}const l=s(t,["finishReason"]);if(l!=null){a(n,["finishReason"],l)}const u=s(t,["groundingMetadata"]);if(u!=null){a(n,["groundingMetadata"],u)}const c=s(t,["avgLogprobs"]);if(c!=null){a(n,["avgLogprobs"],c)}const d=s(t,["index"]);if(d!=null){a(n,["index"],d)}const f=s(t,["logprobsResult"]);if(f!=null){a(n,["logprobsResult"],f)}const p=s(t,["safetyRatings"]);if(p!=null){let m=p;if(Array.isArray(m)){m=m.map(_=>{return _})}a(n,["safetyRatings"],m)}const h=s(t,["urlContextMetadata"]);if(h!=null){a(n,["urlContextMetadata"],h)}return n}function TT(t,e){const n={};const i=s(t,["citationSources"]);if(i!=null){let r=i;if(Array.isArray(r)){r=r.map(o=>{return o})}a(n,["citations"],r)}return n}function AT(t,e,n){const i={};const r=s(e,["model"]);if(r!=null){a(i,["_url","model"],j(t,r))}const o=s(e,["contents"]);if(o!=null){let l=Ae(o);if(Array.isArray(l)){l=l.map(u=>{return on(u)})}a(i,["contents"],l)}return i}function CT(t,e){const n={};const i=s(t,["sdkHttpResponse"]);if(i!=null){a(n,["sdkHttpResponse"],i)}const r=s(t,["tokensInfo"]);if(r!=null){let o=r;if(Array.isArray(o)){o=o.map(l=>{return l})}a(n,["tokensInfo"],o)}return n}function vT(t,e){const n={};const i=s(t,["values"]);if(i!=null){a(n,["values"],i)}const r=s(t,["statistics"]);if(r!=null){a(n,["statistics"],ST(r))}return n}function ST(t,e){const n={};const i=s(t,["truncated"]);if(i!=null){a(n,["truncated"],i)}const r=s(t,["token_count"]);if(r!=null){a(n,["tokenCount"],r)}return n}function Nn(t,e){const n={};const i=s(t,["parts"]);if(i!=null){let o=i;if(Array.isArray(o)){o=o.map(l=>{return DA(l)})}a(n,["parts"],o)}const r=s(t,["role"]);if(r!=null){a(n,["role"],r)}return n}function on(t,e){const n={};const i=s(t,["parts"]);if(i!=null){let o=i;if(Array.isArray(o)){o=o.map(l=>{return UA(l)})}a(n,["parts"],o)}const r=s(t,["role"]);if(r!=null){a(n,["role"],r)}return n}function IT(t,e){const n={};const i=s(t,["controlType"]);if(i!=null){a(n,["controlType"],i)}const r=s(t,["enableControlImageComputation"]);if(r!=null){a(n,["computeControl"],r)}return n}function wT(t,e){const n={};if(s(t,["systemInstruction"])!==void 0){throw new Error("systemInstruction parameter is not supported in Gemini API.")}if(s(t,["tools"])!==void 0){throw new Error("tools parameter is not supported in Gemini API.")}if(s(t,["generationConfig"])!==void 0){throw new Error("generationConfig parameter is not supported in Gemini API.")}return n}function RT(t,e,n){const i={};const r=s(t,["systemInstruction"]);if(e!==void 0&&r!=null){a(e,["systemInstruction"],on(he(r)))}const o=s(t,["tools"]);if(e!==void 0&&o!=null){let u=o;if(Array.isArray(u)){u=u.map(c=>{return Df(c)})}a(e,["tools"],u)}const l=s(t,["generationConfig"]);if(e!==void 0&&l!=null){a(e,["generationConfig"],EA(l))}return i}function PT(t,e,n){const i={};const r=s(e,["model"]);if(r!=null){a(i,["_url","model"],j(t,r))}const o=s(e,["contents"]);if(o!=null){let u=Ae(o);if(Array.isArray(u)){u=u.map(c=>{return Nn(c)})}a(i,["contents"],u)}const l=s(e,["config"]);if(l!=null){wT(l)}return i}function NT(t,e,n){const i={};const r=s(e,["model"]);if(r!=null){a(i,["_url","model"],j(t,r))}const o=s(e,["contents"]);if(o!=null){let u=Ae(o);if(Array.isArray(u)){u=u.map(c=>{return on(c)})}a(i,["contents"],u)}const l=s(e,["config"]);if(l!=null){RT(l,i)}return i}function MT(t,e){const n={};const i=s(t,["sdkHttpResponse"]);if(i!=null){a(n,["sdkHttpResponse"],i)}const r=s(t,["totalTokens"]);if(r!=null){a(n,["totalTokens"],r)}const o=s(t,["cachedContentTokenCount"]);if(o!=null){a(n,["cachedContentTokenCount"],o)}return n}function kT(t,e){const n={};const i=s(t,["sdkHttpResponse"]);if(i!=null){a(n,["sdkHttpResponse"],i)}const r=s(t,["totalTokens"]);if(r!=null){a(n,["totalTokens"],r)}return n}function xT(t,e,n){const i={};const r=s(e,["model"]);if(r!=null){a(i,["_url","name"],j(t,r))}return i}function DT(t,e,n){const i={};const r=s(e,["model"]);if(r!=null){a(i,["_url","name"],j(t,r))}return i}function UT(t,e){const n={};const i=s(t,["sdkHttpResponse"]);if(i!=null){a(n,["sdkHttpResponse"],i)}return n}function LT(t,e){const n={};const i=s(t,["sdkHttpResponse"]);if(i!=null){a(n,["sdkHttpResponse"],i)}return n}function GT(t,e,n){const i={};const r=s(t,["outputGcsUri"]);if(e!==void 0&&r!=null){a(e,["parameters","storageUri"],r)}const o=s(t,["negativePrompt"]);if(e!==void 0&&o!=null){a(e,["parameters","negativePrompt"],o)}const l=s(t,["numberOfImages"]);if(e!==void 0&&l!=null){a(e,["parameters","sampleCount"],l)}const u=s(t,["aspectRatio"]);if(e!==void 0&&u!=null){a(e,["parameters","aspectRatio"],u)}const c=s(t,["guidanceScale"]);if(e!==void 0&&c!=null){a(e,["parameters","guidanceScale"],c)}const d=s(t,["seed"]);if(e!==void 0&&d!=null){a(e,["parameters","seed"],d)}const f=s(t,["safetyFilterLevel"]);if(e!==void 0&&f!=null){a(e,["parameters","safetySetting"],f)}const p=s(t,["personGeneration"]);if(e!==void 0&&p!=null){a(e,["parameters","personGeneration"],p)}const h=s(t,["includeSafetyAttributes"]);if(e!==void 0&&h!=null){a(e,["parameters","includeSafetyAttributes"],h)}const m=s(t,["includeRaiReason"]);if(e!==void 0&&m!=null){a(e,["parameters","includeRaiReason"],m)}const _=s(t,["language"]);if(e!==void 0&&_!=null){a(e,["parameters","language"],_)}const A=s(t,["outputMimeType"]);if(e!==void 0&&A!=null){a(e,["parameters","outputOptions","mimeType"],A)}const T=s(t,["outputCompressionQuality"]);if(e!==void 0&&T!=null){a(e,["parameters","outputOptions","compressionQuality"],T)}const v=s(t,["addWatermark"]);if(e!==void 0&&v!=null){a(e,["parameters","addWatermark"],v)}const G=s(t,["labels"]);if(e!==void 0&&G!=null){a(e,["labels"],G)}const D=s(t,["editMode"]);if(e!==void 0&&D!=null){a(e,["parameters","editMode"],D)}const O=s(t,["baseSteps"]);if(e!==void 0&&O!=null){a(e,["parameters","editConfig","baseSteps"],O)}return i}function OT(t,e,n){const i={};const r=s(e,["model"]);if(r!=null){a(i,["_url","model"],j(t,r))}const o=s(e,["prompt"]);if(o!=null){a(i,["instances[0]","prompt"],o)}const l=s(e,["referenceImages"]);if(l!=null){let c=l;if(Array.isArray(c)){c=c.map(d=>{return qA(d)})}a(i,["instances[0]","referenceImages"],c)}const u=s(e,["config"]);if(u!=null){GT(u,i)}return i}function bT(t,e){const n={};const i=s(t,["sdkHttpResponse"]);if(i!=null){a(n,["sdkHttpResponse"],i)}const r=s(t,["predictions"]);if(r!=null){let o=r;if(Array.isArray(o)){o=o.map(l=>{return mr(l)})}a(n,["generatedImages"],o)}return n}function FT(t,e,n){const i={};const r=s(t,["taskType"]);if(e!==void 0&&r!=null){a(e,["requests[]","taskType"],r)}const o=s(t,["title"]);if(e!==void 0&&o!=null){a(e,["requests[]","title"],o)}const l=s(t,["outputDimensionality"]);if(e!==void 0&&l!=null){a(e,["requests[]","outputDimensionality"],l)}if(s(t,["mimeType"])!==void 0){throw new Error("mimeType parameter is not supported in Gemini API.")}if(s(t,["autoTruncate"])!==void 0){throw new Error("autoTruncate parameter is not supported in Gemini API.")}if(s(t,["documentOcr"])!==void 0){throw new Error("documentOcr parameter is not supported in Gemini API.")}if(s(t,["audioTrackExtraction"])!==void 0){throw new Error("audioTrackExtraction parameter is not supported in Gemini API.")}return i}function qT(t,e,n){const i={};let r=s(n,["embeddingApiType"]);if(r===void 0){r="PREDICT"}if(r==="PREDICT"){const p=s(t,["taskType"]);if(e!==void 0&&p!=null){a(e,["instances[]","task_type"],p)}}else if(r==="EMBED_CONTENT"){const p=s(t,["taskType"]);if(e!==void 0&&p!=null){a(e,["embedContentConfig","taskType"],p)}}let o=s(n,["embeddingApiType"]);if(o===void 0){o="PREDICT"}if(o==="PREDICT"){const p=s(t,["title"]);if(e!==void 0&&p!=null){a(e,["instances[]","title"],p)}}else if(o==="EMBED_CONTENT"){const p=s(t,["title"]);if(e!==void 0&&p!=null){a(e,["embedContentConfig","title"],p)}}let l=s(n,["embeddingApiType"]);if(l===void 0){l="PREDICT"}if(l==="PREDICT"){const p=s(t,["outputDimensionality"]);if(e!==void 0&&p!=null){a(e,["parameters","outputDimensionality"],p)}}else if(l==="EMBED_CONTENT"){const p=s(t,["outputDimensionality"]);if(e!==void 0&&p!=null){a(e,["embedContentConfig","outputDimensionality"],p)}}let u=s(n,["embeddingApiType"]);if(u===void 0){u="PREDICT"}if(u==="PREDICT"){const p=s(t,["mimeType"]);if(e!==void 0&&p!=null){a(e,["instances[]","mimeType"],p)}}let c=s(n,["embeddingApiType"]);if(c===void 0){c="PREDICT"}if(c==="PREDICT"){const p=s(t,["autoTruncate"]);if(e!==void 0&&p!=null){a(e,["parameters","autoTruncate"],p)}}else if(c==="EMBED_CONTENT"){const p=s(t,["autoTruncate"]);if(e!==void 0&&p!=null){a(e,["embedContentConfig","autoTruncate"],p)}}let d=s(n,["embeddingApiType"]);if(d===void 0){d="PREDICT"}if(d==="EMBED_CONTENT"){const p=s(t,["documentOcr"]);if(e!==void 0&&p!=null){a(e,["embedContentConfig","documentOcr"],p)}}let f=s(n,["embeddingApiType"]);if(f===void 0){f="PREDICT"}if(f==="EMBED_CONTENT"){const p=s(t,["audioTrackExtraction"]);if(e!==void 0&&p!=null){a(e,["embedContentConfig","audioTrackExtraction"],p)}}return i}function HT(t,e,n){const i={};const r=s(e,["model"]);if(r!=null){a(i,["_url","model"],j(t,r))}const o=s(e,["contents"]);if(o!=null){let d=La(t,o);if(Array.isArray(d)){d=d.map(f=>{return f})}a(i,["requests[]","content"],d)}const l=s(e,["content"]);if(l!=null){Nn(he(l))}const u=s(e,["config"]);if(u!=null){FT(u,i)}const c=s(e,["model"]);if(c!==void 0){a(i,["requests[]","model"],j(t,c))}return i}function VT(t,e,n){const i={};const r=s(e,["model"]);if(r!=null){a(i,["_url","model"],j(t,r))}let o=s(n,["embeddingApiType"]);if(o===void 0){o="PREDICT"}if(o==="PREDICT"){const c=s(e,["contents"]);if(c!=null){let d=La(t,c);if(Array.isArray(d)){d=d.map(f=>{return f})}a(i,["instances[]","content"],d)}}let l=s(n,["embeddingApiType"]);if(l===void 0){l="PREDICT"}if(l==="EMBED_CONTENT"){const c=s(e,["content"]);if(c!=null){a(i,["content"],on(he(c)))}}const u=s(e,["config"]);if(u!=null){qT(u,i,n)}return i}function BT(t,e){const n={};const i=s(t,["sdkHttpResponse"]);if(i!=null){a(n,["sdkHttpResponse"],i)}const r=s(t,["embeddings"]);if(r!=null){let l=r;if(Array.isArray(l)){l=l.map(u=>{return u})}a(n,["embeddings"],l)}const o=s(t,["metadata"]);if(o!=null){a(n,["metadata"],o)}return n}function $T(t,e){const n={};const i=s(t,["sdkHttpResponse"]);if(i!=null){a(n,["sdkHttpResponse"],i)}const r=s(t,["predictions[]","embeddings"]);if(r!=null){let l=r;if(Array.isArray(l)){l=l.map(u=>{return vT(u)})}a(n,["embeddings"],l)}const o=s(t,["metadata"]);if(o!=null){a(n,["metadata"],o)}if(e&&s(e,["embeddingApiType"])==="EMBED_CONTENT"){const l=s(t,["embedding"]);const u=s(t,["usageMetadata"]);const c=s(t,["truncated"]);if(l){const d={};if(u&&u["promptTokenCount"]){d.tokenCount=u["promptTokenCount"]}if(c){d.truncated=c}l.statistics=d;a(n,["embeddings"],[l])}}return n}function JT(t,e){const n={};const i=s(t,["endpoint"]);if(i!=null){a(n,["name"],i)}const r=s(t,["deployedModelId"]);if(r!=null){a(n,["deployedModelId"],r)}return n}function KT(t,e){const n={};if(s(t,["displayName"])!==void 0){throw new Error("displayName parameter is not supported in Gemini API.")}const i=s(t,["fileUri"]);if(i!=null){a(n,["fileUri"],i)}const r=s(t,["mimeType"]);if(r!=null){a(n,["mimeType"],r)}return n}function WT(t,e){const n={};const i=s(t,["id"]);if(i!=null){a(n,["id"],i)}const r=s(t,["args"]);if(r!=null){a(n,["args"],r)}const o=s(t,["name"]);if(o!=null){a(n,["name"],o)}if(s(t,["partialArgs"])!==void 0){throw new Error("partialArgs parameter is not supported in Gemini API.")}if(s(t,["willContinue"])!==void 0){throw new Error("willContinue parameter is not supported in Gemini API.")}return n}function YT(t,e){const n={};const i=s(t,["allowedFunctionNames"]);if(i!=null){a(n,["allowedFunctionNames"],i)}const r=s(t,["mode"]);if(r!=null){a(n,["mode"],r)}if(s(t,["streamFunctionCallArguments"])!==void 0){throw new Error("streamFunctionCallArguments parameter is not supported in Gemini API.")}return n}function zT(t,e){const n={};const i=s(t,["description"]);if(i!=null){a(n,["description"],i)}const r=s(t,["name"]);if(r!=null){a(n,["name"],r)}const o=s(t,["parameters"]);if(o!=null){a(n,["parameters"],o)}const l=s(t,["parametersJsonSchema"]);if(l!=null){a(n,["parametersJsonSchema"],l)}const u=s(t,["response"]);if(u!=null){a(n,["response"],u)}const c=s(t,["responseJsonSchema"]);if(c!=null){a(n,["responseJsonSchema"],c)}if(s(t,["behavior"])!==void 0){throw new Error("behavior parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).")}return n}function XT(t,e,n,i){const r={};const o=s(e,["systemInstruction"]);if(n!==void 0&&o!=null){a(n,["systemInstruction"],Nn(he(o)))}const l=s(e,["temperature"]);if(l!=null){a(r,["temperature"],l)}const u=s(e,["topP"]);if(u!=null){a(r,["topP"],u)}const c=s(e,["topK"]);if(c!=null){a(r,["topK"],c)}const d=s(e,["candidateCount"]);if(d!=null){a(r,["candidateCount"],d)}const f=s(e,["maxOutputTokens"]);if(f!=null){a(r,["maxOutputTokens"],f)}const p=s(e,["stopSequences"]);if(p!=null){a(r,["stopSequences"],p)}const h=s(e,["responseLogprobs"]);if(h!=null){a(r,["responseLogprobs"],h)}const m=s(e,["logprobs"]);if(m!=null){a(r,["logprobs"],m)}const _=s(e,["presencePenalty"]);if(_!=null){a(r,["presencePenalty"],_)}const A=s(e,["frequencyPenalty"]);if(A!=null){a(r,["frequencyPenalty"],A)}const T=s(e,["seed"]);if(T!=null){a(r,["seed"],T)}const v=s(e,["responseMimeType"]);if(v!=null){a(r,["responseMimeType"],v)}const G=s(e,["responseSchema"]);if(G!=null){a(r,["responseSchema"],Ga(G))}const D=s(e,["responseJsonSchema"]);if(D!=null){a(r,["responseJsonSchema"],D)}if(s(e,["routingConfig"])!==void 0){throw new Error("routingConfig parameter is not supported in Gemini API.")}if(s(e,["modelSelectionConfig"])!==void 0){throw new Error("modelSelectionConfig parameter is not supported in Gemini API.")}const O=s(e,["safetySettings"]);if(n!==void 0&&O!=null){let re=O;if(Array.isArray(re)){re=re.map(le=>{return HA(le)})}a(n,["safetySettings"],re)}const L=s(e,["tools"]);if(n!==void 0&&L!=null){let re=nn(L);if(Array.isArray(re)){re=re.map(le=>{return zA(tn(le))})}a(n,["tools"],re)}const R=s(e,["toolConfig"]);if(n!==void 0&&R!=null){a(n,["toolConfig"],WA(R))}if(s(e,["labels"])!==void 0){throw new Error("labels parameter is not supported in Gemini API.")}const q=s(e,["cachedContent"]);if(n!==void 0&&q!=null){a(n,["cachedContent"],lt(t,q))}const V=s(e,["responseModalities"]);if(V!=null){a(r,["responseModalities"],V)}const k=s(e,["mediaResolution"]);if(k!=null){a(r,["mediaResolution"],k)}const $=s(e,["speechConfig"]);if($!=null){a(r,["speechConfig"],Oa($))}if(s(e,["audioTimestamp"])!==void 0){throw new Error("audioTimestamp parameter is not supported in Gemini API.")}const Y=s(e,["thinkingConfig"]);if(Y!=null){a(r,["thinkingConfig"],Y)}const Q=s(e,["imageConfig"]);if(Q!=null){a(r,["imageConfig"],vA(Q))}const oe=s(e,["enableEnhancedCivicAnswers"]);if(oe!=null){a(r,["enableEnhancedCivicAnswers"],oe)}if(s(e,["modelArmorConfig"])!==void 0){throw new Error("modelArmorConfig parameter is not supported in Gemini API.")}const ee=s(e,["serviceTier"]);if(n!==void 0&&ee!=null){a(n,["serviceTier"],ee)}return r}function QT(t,e,n,i){const r={};const o=s(e,["systemInstruction"]);if(n!==void 0&&o!=null){a(n,["systemInstruction"],on(he(o)))}const l=s(e,["temperature"]);if(l!=null){a(r,["temperature"],l)}const u=s(e,["topP"]);if(u!=null){a(r,["topP"],u)}const c=s(e,["topK"]);if(c!=null){a(r,["topK"],c)}const d=s(e,["candidateCount"]);if(d!=null){a(r,["candidateCount"],d)}const f=s(e,["maxOutputTokens"]);if(f!=null){a(r,["maxOutputTokens"],f)}const p=s(e,["stopSequences"]);if(p!=null){a(r,["stopSequences"],p)}const h=s(e,["responseLogprobs"]);if(h!=null){a(r,["responseLogprobs"],h)}const m=s(e,["logprobs"]);if(m!=null){a(r,["logprobs"],m)}const _=s(e,["presencePenalty"]);if(_!=null){a(r,["presencePenalty"],_)}const A=s(e,["frequencyPenalty"]);if(A!=null){a(r,["frequencyPenalty"],A)}const T=s(e,["seed"]);if(T!=null){a(r,["seed"],T)}const v=s(e,["responseMimeType"]);if(v!=null){a(r,["responseMimeType"],v)}const G=s(e,["responseSchema"]);if(G!=null){a(r,["responseSchema"],Ga(G))}const D=s(e,["responseJsonSchema"]);if(D!=null){a(r,["responseJsonSchema"],D)}const O=s(e,["routingConfig"]);if(O!=null){a(r,["routingConfig"],O)}const L=s(e,["modelSelectionConfig"]);if(L!=null){a(r,["modelConfig"],L)}const R=s(e,["safetySettings"]);if(n!==void 0&&R!=null){let ce=R;if(Array.isArray(ce)){ce=ce.map(At=>{return At})}a(n,["safetySettings"],ce)}const q=s(e,["tools"]);if(n!==void 0&&q!=null){let ce=nn(q);if(Array.isArray(ce)){ce=ce.map(At=>{return Df(tn(At))})}a(n,["tools"],ce)}const V=s(e,["toolConfig"]);if(n!==void 0&&V!=null){a(n,["toolConfig"],YA(V))}const k=s(e,["labels"]);if(n!==void 0&&k!=null){a(n,["labels"],k)}const $=s(e,["cachedContent"]);if(n!==void 0&&$!=null){a(n,["cachedContent"],lt(t,$))}const Y=s(e,["responseModalities"]);if(Y!=null){a(r,["responseModalities"],Y)}const Q=s(e,["mediaResolution"]);if(Q!=null){a(r,["mediaResolution"],Q)}const oe=s(e,["speechConfig"]);if(oe!=null){a(r,["speechConfig"],Oa(oe))}const ee=s(e,["audioTimestamp"]);if(ee!=null){a(r,["audioTimestamp"],ee)}const re=s(e,["thinkingConfig"]);if(re!=null){a(r,["thinkingConfig"],re)}const le=s(e,["imageConfig"]);if(le!=null){a(r,["imageConfig"],SA(le))}if(s(e,["enableEnhancedCivicAnswers"])!==void 0){throw new Error("enableEnhancedCivicAnswers parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).")}const Se=s(e,["modelArmorConfig"]);if(n!==void 0&&Se!=null){a(n,["modelArmorConfig"],Se)}const Ie=s(e,["serviceTier"]);if(n!==void 0&&Ie!=null){a(n,["serviceTier"],Ie)}return r}function Wd(t,e,n){const i={};const r=s(e,["model"]);if(r!=null){a(i,["_url","model"],j(t,r))}const o=s(e,["contents"]);if(o!=null){let u=Ae(o);if(Array.isArray(u)){u=u.map(c=>{return Nn(c)})}a(i,["contents"],u)}const l=s(e,["config"]);if(l!=null){a(i,["generationConfig"],XT(t,l,i))}return i}function Yd(t,e,n){const i={};const r=s(e,["model"]);if(r!=null){a(i,["_url","model"],j(t,r))}const o=s(e,["contents"]);if(o!=null){let u=Ae(o);if(Array.isArray(u)){u=u.map(c=>{return on(c)})}a(i,["contents"],u)}const l=s(e,["config"]);if(l!=null){a(i,["generationConfig"],QT(t,l,i))}return i}function zd(t,e){const n={};const i=s(t,["sdkHttpResponse"]);if(i!=null){a(n,["sdkHttpResponse"],i)}const r=s(t,["candidates"]);if(r!=null){let f=r;if(Array.isArray(f)){f=f.map(p=>{return _T(p)})}a(n,["candidates"],f)}const o=s(t,["modelVersion"]);if(o!=null){a(n,["modelVersion"],o)}const l=s(t,["promptFeedback"]);if(l!=null){a(n,["promptFeedback"],l)}const u=s(t,["responseId"]);if(u!=null){a(n,["responseId"],u)}const c=s(t,["usageMetadata"]);if(c!=null){a(n,["usageMetadata"],c)}const d=s(t,["modelStatus"]);if(d!=null){a(n,["modelStatus"],d)}return n}function Xd(t,e){const n={};const i=s(t,["sdkHttpResponse"]);if(i!=null){a(n,["sdkHttpResponse"],i)}const r=s(t,["candidates"]);if(r!=null){let f=r;if(Array.isArray(f)){f=f.map(p=>{return p})}a(n,["candidates"],f)}const o=s(t,["createTime"]);if(o!=null){a(n,["createTime"],o)}const l=s(t,["modelVersion"]);if(l!=null){a(n,["modelVersion"],l)}const u=s(t,["promptFeedback"]);if(u!=null){a(n,["promptFeedback"],u)}const c=s(t,["responseId"]);if(c!=null){a(n,["responseId"],c)}const d=s(t,["usageMetadata"]);if(d!=null){a(n,["usageMetadata"],d)}return n}function ZT(t,e,n){const i={};if(s(t,["outputGcsUri"])!==void 0){throw new Error("outputGcsUri parameter is not supported in Gemini API.")}if(s(t,["negativePrompt"])!==void 0){throw new Error("negativePrompt parameter is not supported in Gemini API.")}const r=s(t,["numberOfImages"]);if(e!==void 0&&r!=null){a(e,["parameters","sampleCount"],r)}const o=s(t,["aspectRatio"]);if(e!==void 0&&o!=null){a(e,["parameters","aspectRatio"],o)}const l=s(t,["guidanceScale"]);if(e!==void 0&&l!=null){a(e,["parameters","guidanceScale"],l)}if(s(t,["seed"])!==void 0){throw new Error("seed parameter is not supported in Gemini API.")}const u=s(t,["safetyFilterLevel"]);if(e!==void 0&&u!=null){a(e,["parameters","safetySetting"],u)}const c=s(t,["personGeneration"]);if(e!==void 0&&c!=null){a(e,["parameters","personGeneration"],c)}const d=s(t,["includeSafetyAttributes"]);if(e!==void 0&&d!=null){a(e,["parameters","includeSafetyAttributes"],d)}const f=s(t,["includeRaiReason"]);if(e!==void 0&&f!=null){a(e,["parameters","includeRaiReason"],f)}const p=s(t,["language"]);if(e!==void 0&&p!=null){a(e,["parameters","language"],p)}const h=s(t,["outputMimeType"]);if(e!==void 0&&h!=null){a(e,["parameters","outputOptions","mimeType"],h)}const m=s(t,["outputCompressionQuality"]);if(e!==void 0&&m!=null){a(e,["parameters","outputOptions","compressionQuality"],m)}if(s(t,["addWatermark"])!==void 0){throw new Error("addWatermark parameter is not supported in Gemini API.")}if(s(t,["labels"])!==void 0){throw new Error("labels parameter is not supported in Gemini API.")}const _=s(t,["imageSize"]);if(e!==void 0&&_!=null){a(e,["parameters","sampleImageSize"],_)}if(s(t,["enhancePrompt"])!==void 0){throw new Error("enhancePrompt parameter is not supported in Gemini API.")}return i}function jT(t,e,n){const i={};const r=s(t,["outputGcsUri"]);if(e!==void 0&&r!=null){a(e,["parameters","storageUri"],r)}const o=s(t,["negativePrompt"]);if(e!==void 0&&o!=null){a(e,["parameters","negativePrompt"],o)}const l=s(t,["numberOfImages"]);if(e!==void 0&&l!=null){a(e,["parameters","sampleCount"],l)}const u=s(t,["aspectRatio"]);if(e!==void 0&&u!=null){a(e,["parameters","aspectRatio"],u)}const c=s(t,["guidanceScale"]);if(e!==void 0&&c!=null){a(e,["parameters","guidanceScale"],c)}const d=s(t,["seed"]);if(e!==void 0&&d!=null){a(e,["parameters","seed"],d)}const f=s(t,["safetyFilterLevel"]);if(e!==void 0&&f!=null){a(e,["parameters","safetySetting"],f)}const p=s(t,["personGeneration"]);if(e!==void 0&&p!=null){a(e,["parameters","personGeneration"],p)}const h=s(t,["includeSafetyAttributes"]);if(e!==void 0&&h!=null){a(e,["parameters","includeSafetyAttributes"],h)}const m=s(t,["includeRaiReason"]);if(e!==void 0&&m!=null){a(e,["parameters","includeRaiReason"],m)}const _=s(t,["language"]);if(e!==void 0&&_!=null){a(e,["parameters","language"],_)}const A=s(t,["outputMimeType"]);if(e!==void 0&&A!=null){a(e,["parameters","outputOptions","mimeType"],A)}const T=s(t,["outputCompressionQuality"]);if(e!==void 0&&T!=null){a(e,["parameters","outputOptions","compressionQuality"],T)}const v=s(t,["addWatermark"]);if(e!==void 0&&v!=null){a(e,["parameters","addWatermark"],v)}const G=s(t,["labels"]);if(e!==void 0&&G!=null){a(e,["labels"],G)}const D=s(t,["imageSize"]);if(e!==void 0&&D!=null){a(e,["parameters","sampleImageSize"],D)}const O=s(t,["enhancePrompt"]);if(e!==void 0&&O!=null){a(e,["parameters","enhancePrompt"],O)}return i}function eA(t,e,n){const i={};const r=s(e,["model"]);if(r!=null){a(i,["_url","model"],j(t,r))}const o=s(e,["prompt"]);if(o!=null){a(i,["instances[0]","prompt"],o)}const l=s(e,["config"]);if(l!=null){ZT(l,i)}return i}function tA(t,e,n){const i={};const r=s(e,["model"]);if(r!=null){a(i,["_url","model"],j(t,r))}const o=s(e,["prompt"]);if(o!=null){a(i,["instances[0]","prompt"],o)}const l=s(e,["config"]);if(l!=null){jT(l,i)}return i}function nA(t,e){const n={};const i=s(t,["sdkHttpResponse"]);if(i!=null){a(n,["sdkHttpResponse"],i)}const r=s(t,["predictions"]);if(r!=null){let l=r;if(Array.isArray(l)){l=l.map(u=>{return hA(u)})}a(n,["generatedImages"],l)}const o=s(t,["positivePromptSafetyAttributes"]);if(o!=null){a(n,["positivePromptSafetyAttributes"],kf(o))}return n}function iA(t,e){const n={};const i=s(t,["sdkHttpResponse"]);if(i!=null){a(n,["sdkHttpResponse"],i)}const r=s(t,["predictions"]);if(r!=null){let l=r;if(Array.isArray(l)){l=l.map(u=>{return mr(u)})}a(n,["generatedImages"],l)}const o=s(t,["positivePromptSafetyAttributes"]);if(o!=null){a(n,["positivePromptSafetyAttributes"],xf(o))}return n}function rA(t,e,n){const i={};const r=s(t,["numberOfVideos"]);if(e!==void 0&&r!=null){a(e,["parameters","sampleCount"],r)}if(s(t,["outputGcsUri"])!==void 0){throw new Error("outputGcsUri parameter is not supported in Gemini API.")}if(s(t,["fps"])!==void 0){throw new Error("fps parameter is not supported in Gemini API.")}const o=s(t,["durationSeconds"]);if(e!==void 0&&o!=null){a(e,["parameters","durationSeconds"],o)}if(s(t,["seed"])!==void 0){throw new Error("seed parameter is not supported in Gemini API.")}const l=s(t,["aspectRatio"]);if(e!==void 0&&l!=null){a(e,["parameters","aspectRatio"],l)}const u=s(t,["resolution"]);if(e!==void 0&&u!=null){a(e,["parameters","resolution"],u)}const c=s(t,["personGeneration"]);if(e!==void 0&&c!=null){a(e,["parameters","personGeneration"],c)}if(s(t,["pubsubTopic"])!==void 0){throw new Error("pubsubTopic parameter is not supported in Gemini API.")}const d=s(t,["negativePrompt"]);if(e!==void 0&&d!=null){a(e,["parameters","negativePrompt"],d)}const f=s(t,["enhancePrompt"]);if(e!==void 0&&f!=null){a(e,["parameters","enhancePrompt"],f)}if(s(t,["generateAudio"])!==void 0){throw new Error("generateAudio parameter is not supported in Gemini API.")}const p=s(t,["lastFrame"]);if(e!==void 0&&p!=null){a(e,["instances[0]","lastFrame"],yr(p))}const h=s(t,["referenceImages"]);if(e!==void 0&&h!=null){let _=h;if(Array.isArray(_)){_=_.map(A=>{return lC(A)})}a(e,["instances[0]","referenceImages"],_)}if(s(t,["mask"])!==void 0){throw new Error("mask parameter is not supported in Gemini API.")}if(s(t,["compressionQuality"])!==void 0){throw new Error("compressionQuality parameter is not supported in Gemini API.")}if(s(t,["labels"])!==void 0){throw new Error("labels parameter is not supported in Gemini API.")}const m=s(t,["webhookConfig"]);if(e!==void 0&&m!=null){a(e,["webhookConfig"],m)}if(s(t,["resizeMode"])!==void 0){throw new Error("resizeMode parameter is not supported in Gemini API.")}return i}function oA(t,e,n){const i={};const r=s(t,["numberOfVideos"]);if(e!==void 0&&r!=null){a(e,["parameters","sampleCount"],r)}const o=s(t,["outputGcsUri"]);if(e!==void 0&&o!=null){a(e,["parameters","storageUri"],o)}const l=s(t,["fps"]);if(e!==void 0&&l!=null){a(e,["parameters","fps"],l)}const u=s(t,["durationSeconds"]);if(e!==void 0&&u!=null){a(e,["parameters","durationSeconds"],u)}const c=s(t,["seed"]);if(e!==void 0&&c!=null){a(e,["parameters","seed"],c)}const d=s(t,["aspectRatio"]);if(e!==void 0&&d!=null){a(e,["parameters","aspectRatio"],d)}const f=s(t,["resolution"]);if(e!==void 0&&f!=null){a(e,["parameters","resolution"],f)}const p=s(t,["personGeneration"]);if(e!==void 0&&p!=null){a(e,["parameters","personGeneration"],p)}const h=s(t,["pubsubTopic"]);if(e!==void 0&&h!=null){a(e,["parameters","pubsubTopic"],h)}const m=s(t,["negativePrompt"]);if(e!==void 0&&m!=null){a(e,["parameters","negativePrompt"],m)}const _=s(t,["enhancePrompt"]);if(e!==void 0&&_!=null){a(e,["parameters","enhancePrompt"],_)}const A=s(t,["generateAudio"]);if(e!==void 0&&A!=null){a(e,["parameters","generateAudio"],A)}const T=s(t,["lastFrame"]);if(e!==void 0&&T!=null){a(e,["instances[0]","lastFrame"],Ye(T))}const v=s(t,["referenceImages"]);if(e!==void 0&&v!=null){let R=v;if(Array.isArray(R)){R=R.map(q=>{return uC(q)})}a(e,["instances[0]","referenceImages"],R)}const G=s(t,["mask"]);if(e!==void 0&&G!=null){a(e,["instances[0]","mask"],aC(G))}const D=s(t,["compressionQuality"]);if(e!==void 0&&D!=null){a(e,["parameters","compressionQuality"],D)}const O=s(t,["labels"]);if(e!==void 0&&O!=null){a(e,["labels"],O)}if(s(t,["webhookConfig"])!==void 0){throw new Error("webhookConfig parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).")}const L=s(t,["resizeMode"]);if(e!==void 0&&L!=null){a(e,["parameters","resizeMode"],L)}return i}function sA(t,e){const n={};const i=s(t,["name"]);if(i!=null){a(n,["name"],i)}const r=s(t,["metadata"]);if(r!=null){a(n,["metadata"],r)}const o=s(t,["done"]);if(o!=null){a(n,["done"],o)}const l=s(t,["error"]);if(l!=null){a(n,["error"],l)}const u=s(t,["response","generateVideoResponse"]);if(u!=null){a(n,["response"],cA(u))}return n}function aA(t,e){const n={};const i=s(t,["name"]);if(i!=null){a(n,["name"],i)}const r=s(t,["metadata"]);if(r!=null){a(n,["metadata"],r)}const o=s(t,["done"]);if(o!=null){a(n,["done"],o)}const l=s(t,["error"]);if(l!=null){a(n,["error"],l)}const u=s(t,["response"]);if(u!=null){a(n,["response"],dA(u))}return n}function lA(t,e,n){const i={};const r=s(e,["model"]);if(r!=null){a(i,["_url","model"],j(t,r))}const o=s(e,["prompt"]);if(o!=null){a(i,["instances[0]","prompt"],o)}const l=s(e,["image"]);if(l!=null){a(i,["instances[0]","image"],yr(l))}const u=s(e,["video"]);if(u!=null){a(i,["instances[0]","video"],Uf(u))}const c=s(e,["source"]);if(c!=null){fA(c,i)}const d=s(e,["config"]);if(d!=null){rA(d,i)}return i}function uA(t,e,n){const i={};const r=s(e,["model"]);if(r!=null){a(i,["_url","model"],j(t,r))}const o=s(e,["prompt"]);if(o!=null){a(i,["instances[0]","prompt"],o)}const l=s(e,["image"]);if(l!=null){a(i,["instances[0]","image"],Ye(l))}const u=s(e,["video"]);if(u!=null){a(i,["instances[0]","video"],Lf(u))}const c=s(e,["source"]);if(c!=null){pA(c,i)}const d=s(e,["config"]);if(d!=null){oA(d,i)}return i}function cA(t,e){const n={};const i=s(t,["generatedSamples"]);if(i!=null){let l=i;if(Array.isArray(l)){l=l.map(u=>{return mA(u)})}a(n,["generatedVideos"],l)}const r=s(t,["raiMediaFilteredCount"]);if(r!=null){a(n,["raiMediaFilteredCount"],r)}const o=s(t,["raiMediaFilteredReasons"]);if(o!=null){a(n,["raiMediaFilteredReasons"],o)}return n}function dA(t,e){const n={};const i=s(t,["videos"]);if(i!=null){let l=i;if(Array.isArray(l)){l=l.map(u=>{return yA(u)})}a(n,["generatedVideos"],l)}const r=s(t,["raiMediaFilteredCount"]);if(r!=null){a(n,["raiMediaFilteredCount"],r)}const o=s(t,["raiMediaFilteredReasons"]);if(o!=null){a(n,["raiMediaFilteredReasons"],o)}return n}function fA(t,e,n){const i={};const r=s(t,["prompt"]);if(e!==void 0&&r!=null){a(e,["instances[0]","prompt"],r)}const o=s(t,["image"]);if(e!==void 0&&o!=null){a(e,["instances[0]","image"],yr(o))}const l=s(t,["video"]);if(e!==void 0&&l!=null){a(e,["instances[0]","video"],Uf(l))}return i}function pA(t,e,n){const i={};const r=s(t,["prompt"]);if(e!==void 0&&r!=null){a(e,["instances[0]","prompt"],r)}const o=s(t,["image"]);if(e!==void 0&&o!=null){a(e,["instances[0]","image"],Ye(o))}const l=s(t,["video"]);if(e!==void 0&&l!=null){a(e,["instances[0]","video"],Lf(l))}return i}function hA(t,e){const n={};const i=s(t,["_self"]);if(i!=null){a(n,["image"],IA(i))}const r=s(t,["raiFilteredReason"]);if(r!=null){a(n,["raiFilteredReason"],r)}const o=s(t,["_self"]);if(o!=null){a(n,["safetyAttributes"],kf(o))}return n}function mr(t,e){const n={};const i=s(t,["_self"]);if(i!=null){a(n,["image"],Mf(i))}const r=s(t,["raiFilteredReason"]);if(r!=null){a(n,["raiFilteredReason"],r)}const o=s(t,["_self"]);if(o!=null){a(n,["safetyAttributes"],xf(o))}const l=s(t,["prompt"]);if(l!=null){a(n,["enhancedPrompt"],l)}return n}function gA(t,e){const n={};const i=s(t,["_self"]);if(i!=null){a(n,["mask"],Mf(i))}const r=s(t,["labels"]);if(r!=null){let o=r;if(Array.isArray(o)){o=o.map(l=>{return l})}a(n,["labels"],o)}return n}function mA(t,e){const n={};const i=s(t,["video"]);if(i!=null){a(n,["video"],oC(i))}return n}function yA(t,e){const n={};const i=s(t,["_self"]);if(i!=null){a(n,["video"],sC(i))}return n}function EA(t,e){const n={};const i=s(t,["modelSelectionConfig"]);if(i!=null){a(n,["modelConfig"],i)}const r=s(t,["responseJsonSchema"]);if(r!=null){a(n,["responseJsonSchema"],r)}const o=s(t,["audioTimestamp"]);if(o!=null){a(n,["audioTimestamp"],o)}const l=s(t,["candidateCount"]);if(l!=null){a(n,["candidateCount"],l)}const u=s(t,["enableAffectiveDialog"]);if(u!=null){a(n,["enableAffectiveDialog"],u)}const c=s(t,["frequencyPenalty"]);if(c!=null){a(n,["frequencyPenalty"],c)}const d=s(t,["logprobs"]);if(d!=null){a(n,["logprobs"],d)}const f=s(t,["maxOutputTokens"]);if(f!=null){a(n,["maxOutputTokens"],f)}const p=s(t,["mediaResolution"]);if(p!=null){a(n,["mediaResolution"],p)}const h=s(t,["presencePenalty"]);if(h!=null){a(n,["presencePenalty"],h)}const m=s(t,["responseLogprobs"]);if(m!=null){a(n,["responseLogprobs"],m)}const _=s(t,["responseMimeType"]);if(_!=null){a(n,["responseMimeType"],_)}const A=s(t,["responseModalities"]);if(A!=null){a(n,["responseModalities"],A)}const T=s(t,["responseSchema"]);if(T!=null){a(n,["responseSchema"],T)}const v=s(t,["routingConfig"]);if(v!=null){a(n,["routingConfig"],v)}const G=s(t,["seed"]);if(G!=null){a(n,["seed"],G)}const D=s(t,["speechConfig"]);if(D!=null){a(n,["speechConfig"],D)}const O=s(t,["stopSequences"]);if(O!=null){a(n,["stopSequences"],O)}const L=s(t,["temperature"]);if(L!=null){a(n,["temperature"],L)}const R=s(t,["thinkingConfig"]);if(R!=null){a(n,["thinkingConfig"],R)}const q=s(t,["topK"]);if(q!=null){a(n,["topK"],q)}const V=s(t,["topP"]);if(V!=null){a(n,["topP"],V)}if(s(t,["enableEnhancedCivicAnswers"])!==void 0){throw new Error("enableEnhancedCivicAnswers parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).")}return n}function _A(t,e,n){const i={};const r=s(e,["model"]);if(r!=null){a(i,["_url","name"],j(t,r))}return i}function TA(t,e,n){const i={};const r=s(e,["model"]);if(r!=null){a(i,["_url","name"],j(t,r))}return i}function AA(t,e){const n={};const i=s(t,["authConfig"]);if(i!=null){a(n,["authConfig"],yT(i))}const r=s(t,["enableWidget"]);if(r!=null){a(n,["enableWidget"],r)}return n}function CA(t,e){const n={};const i=s(t,["searchTypes"]);if(i!=null){a(n,["searchTypes"],i)}if(s(t,["blockingConfidence"])!==void 0){throw new Error("blockingConfidence parameter is not supported in Gemini API.")}if(s(t,["excludeDomains"])!==void 0){throw new Error("excludeDomains parameter is not supported in Gemini API.")}const r=s(t,["timeRangeFilter"]);if(r!=null){a(n,["timeRangeFilter"],r)}return n}function vA(t,e){const n={};const i=s(t,["aspectRatio"]);if(i!=null){a(n,["aspectRatio"],i)}const r=s(t,["imageSize"]);if(r!=null){a(n,["imageSize"],r)}if(s(t,["personGeneration"])!==void 0){throw new Error("personGeneration parameter is not supported in Gemini API.")}if(s(t,["prominentPeople"])!==void 0){throw new Error("prominentPeople parameter is not supported in Gemini API.")}if(s(t,["outputMimeType"])!==void 0){throw new Error("outputMimeType parameter is not supported in Gemini API.")}if(s(t,["outputCompressionQuality"])!==void 0){throw new Error("outputCompressionQuality parameter is not supported in Gemini API.")}if(s(t,["imageOutputOptions"])!==void 0){throw new Error("imageOutputOptions parameter is not supported in Gemini API.")}return n}function SA(t,e){const n={};const i=s(t,["aspectRatio"]);if(i!=null){a(n,["aspectRatio"],i)}const r=s(t,["imageSize"]);if(r!=null){a(n,["imageSize"],r)}const o=s(t,["personGeneration"]);if(o!=null){a(n,["personGeneration"],o)}const l=s(t,["prominentPeople"]);if(l!=null){a(n,["prominentPeople"],l)}const u=s(t,["outputMimeType"]);if(u!=null){a(n,["imageOutputOptions","mimeType"],u)}const c=s(t,["outputCompressionQuality"]);if(c!=null){a(n,["imageOutputOptions","compressionQuality"],c)}const d=s(t,["imageOutputOptions"]);if(d!=null){a(n,["imageOutputOptions"],d)}return n}function IA(t,e){const n={};const i=s(t,["bytesBase64Encoded"]);if(i!=null){a(n,["imageBytes"],Tt(i))}const r=s(t,["mimeType"]);if(r!=null){a(n,["mimeType"],r)}return n}function Mf(t,e){const n={};const i=s(t,["gcsUri"]);if(i!=null){a(n,["gcsUri"],i)}const r=s(t,["bytesBase64Encoded"]);if(r!=null){a(n,["imageBytes"],Tt(r))}const o=s(t,["mimeType"]);if(o!=null){a(n,["mimeType"],o)}return n}function yr(t,e){const n={};if(s(t,["gcsUri"])!==void 0){throw new Error("gcsUri parameter is not supported in Gemini API.")}const i=s(t,["imageBytes"]);if(i!=null){a(n,["bytesBase64Encoded"],Tt(i))}const r=s(t,["mimeType"]);if(r!=null){a(n,["mimeType"],r)}return n}function Ye(t,e){const n={};const i=s(t,["gcsUri"]);if(i!=null){a(n,["gcsUri"],i)}const r=s(t,["imageBytes"]);if(r!=null){a(n,["bytesBase64Encoded"],Tt(r))}const o=s(t,["mimeType"]);if(o!=null){a(n,["mimeType"],o)}return n}function wA(t,e,n,i){const r={};const o=s(e,["pageSize"]);if(n!==void 0&&o!=null){a(n,["_query","pageSize"],o)}const l=s(e,["pageToken"]);if(n!==void 0&&l!=null){a(n,["_query","pageToken"],l)}const u=s(e,["filter"]);if(n!==void 0&&u!=null){a(n,["_query","filter"],u)}const c=s(e,["queryBase"]);if(n!==void 0&&c!=null){a(n,["_url","models_url"],vf(t,c))}return r}function RA(t,e,n,i){const r={};const o=s(e,["pageSize"]);if(n!==void 0&&o!=null){a(n,["_query","pageSize"],o)}const l=s(e,["pageToken"]);if(n!==void 0&&l!=null){a(n,["_query","pageToken"],l)}const u=s(e,["filter"]);if(n!==void 0&&u!=null){a(n,["_query","filter"],u)}const c=s(e,["queryBase"]);if(n!==void 0&&c!=null){a(n,["_url","models_url"],vf(t,c))}return r}function PA(t,e,n){const i={};const r=s(e,["config"]);if(r!=null){wA(t,r,i)}return i}function NA(t,e,n){const i={};const r=s(e,["config"]);if(r!=null){RA(t,r,i)}return i}function MA(t,e){const n={};const i=s(t,["sdkHttpResponse"]);if(i!=null){a(n,["sdkHttpResponse"],i)}const r=s(t,["nextPageToken"]);if(r!=null){a(n,["nextPageToken"],r)}const o=s(t,["_self"]);if(o!=null){let l=Sf(o);if(Array.isArray(l)){l=l.map(u=>{return ra(u)})}a(n,["models"],l)}return n}function kA(t,e){const n={};const i=s(t,["sdkHttpResponse"]);if(i!=null){a(n,["sdkHttpResponse"],i)}const r=s(t,["nextPageToken"]);if(r!=null){a(n,["nextPageToken"],r)}const o=s(t,["_self"]);if(o!=null){let l=Sf(o);if(Array.isArray(l)){l=l.map(u=>{return oa(u)})}a(n,["models"],l)}return n}function xA(t,e){const n={};const i=s(t,["maskMode"]);if(i!=null){a(n,["maskMode"],i)}const r=s(t,["segmentationClasses"]);if(r!=null){a(n,["maskClasses"],r)}const o=s(t,["maskDilation"]);if(o!=null){a(n,["dilation"],o)}return n}function ra(t,e){const n={};const i=s(t,["name"]);if(i!=null){a(n,["name"],i)}const r=s(t,["displayName"]);if(r!=null){a(n,["displayName"],r)}const o=s(t,["description"]);if(o!=null){a(n,["description"],o)}const l=s(t,["version"]);if(l!=null){a(n,["version"],l)}const u=s(t,["_self"]);if(u!=null){a(n,["tunedModelInfo"],XA(u))}const c=s(t,["inputTokenLimit"]);if(c!=null){a(n,["inputTokenLimit"],c)}const d=s(t,["outputTokenLimit"]);if(d!=null){a(n,["outputTokenLimit"],d)}const f=s(t,["supportedGenerationMethods"]);if(f!=null){a(n,["supportedActions"],f)}const p=s(t,["temperature"]);if(p!=null){a(n,["temperature"],p)}const h=s(t,["maxTemperature"]);if(h!=null){a(n,["maxTemperature"],h)}const m=s(t,["topP"]);if(m!=null){a(n,["topP"],m)}const _=s(t,["topK"]);if(_!=null){a(n,["topK"],_)}const A=s(t,["thinking"]);if(A!=null){a(n,["thinking"],A)}return n}function oa(t,e){const n={};const i=s(t,["name"]);if(i!=null){a(n,["name"],i)}const r=s(t,["displayName"]);if(r!=null){a(n,["displayName"],r)}const o=s(t,["description"]);if(o!=null){a(n,["description"],o)}const l=s(t,["versionId"]);if(l!=null){a(n,["version"],l)}const u=s(t,["deployedModels"]);if(u!=null){let h=u;if(Array.isArray(h)){h=h.map(m=>{return JT(m)})}a(n,["endpoints"],h)}const c=s(t,["labels"]);if(c!=null){a(n,["labels"],c)}const d=s(t,["_self"]);if(d!=null){a(n,["tunedModelInfo"],QA(d))}const f=s(t,["defaultCheckpointId"]);if(f!=null){a(n,["defaultCheckpointId"],f)}const p=s(t,["checkpoints"]);if(p!=null){let h=p;if(Array.isArray(h)){h=h.map(m=>{return m})}a(n,["checkpoints"],h)}return n}function DA(t,e){const n={};const i=s(t,["mediaResolution"]);if(i!=null){a(n,["mediaResolution"],i)}const r=s(t,["codeExecutionResult"]);if(r!=null){a(n,["codeExecutionResult"],r)}const o=s(t,["executableCode"]);if(o!=null){a(n,["executableCode"],o)}const l=s(t,["fileData"]);if(l!=null){a(n,["fileData"],KT(l))}const u=s(t,["functionCall"]);if(u!=null){a(n,["functionCall"],WT(u))}const c=s(t,["functionResponse"]);if(c!=null){a(n,["functionResponse"],c)}const d=s(t,["inlineData"]);if(d!=null){a(n,["inlineData"],ET(d))}const f=s(t,["text"]);if(f!=null){a(n,["text"],f)}const p=s(t,["thought"]);if(p!=null){a(n,["thought"],p)}const h=s(t,["thoughtSignature"]);if(h!=null){a(n,["thoughtSignature"],h)}const m=s(t,["videoMetadata"]);if(m!=null){a(n,["videoMetadata"],m)}const _=s(t,["toolCall"]);if(_!=null){a(n,["toolCall"],_)}const A=s(t,["toolResponse"]);if(A!=null){a(n,["toolResponse"],A)}const T=s(t,["partMetadata"]);if(T!=null){a(n,["partMetadata"],T)}return n}function UA(t,e){const n={};const i=s(t,["mediaResolution"]);if(i!=null){a(n,["mediaResolution"],i)}const r=s(t,["codeExecutionResult"]);if(r!=null){a(n,["codeExecutionResult"],r)}const o=s(t,["executableCode"]);if(o!=null){a(n,["executableCode"],o)}const l=s(t,["fileData"]);if(l!=null){a(n,["fileData"],l)}const u=s(t,["functionCall"]);if(u!=null){a(n,["functionCall"],u)}const c=s(t,["functionResponse"]);if(c!=null){a(n,["functionResponse"],c)}const d=s(t,["inlineData"]);if(d!=null){a(n,["inlineData"],d)}const f=s(t,["text"]);if(f!=null){a(n,["text"],f)}const p=s(t,["thought"]);if(p!=null){a(n,["thought"],p)}const h=s(t,["thoughtSignature"]);if(h!=null){a(n,["thoughtSignature"],h)}const m=s(t,["videoMetadata"]);if(m!=null){a(n,["videoMetadata"],m)}if(s(t,["toolCall"])!==void 0){throw new Error("toolCall parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).")}if(s(t,["toolResponse"])!==void 0){throw new Error("toolResponse parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).")}if(s(t,["partMetadata"])!==void 0){throw new Error("partMetadata parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).")}return n}function LA(t,e){const n={};const i=s(t,["productImage"]);if(i!=null){a(n,["image"],Ye(i))}return n}function GA(t,e,n){const i={};const r=s(t,["numberOfImages"]);if(e!==void 0&&r!=null){a(e,["parameters","sampleCount"],r)}const o=s(t,["baseSteps"]);if(e!==void 0&&o!=null){a(e,["parameters","baseSteps"],o)}const l=s(t,["outputGcsUri"]);if(e!==void 0&&l!=null){a(e,["parameters","storageUri"],l)}const u=s(t,["seed"]);if(e!==void 0&&u!=null){a(e,["parameters","seed"],u)}const c=s(t,["safetyFilterLevel"]);if(e!==void 0&&c!=null){a(e,["parameters","safetySetting"],c)}const d=s(t,["personGeneration"]);if(e!==void 0&&d!=null){a(e,["parameters","personGeneration"],d)}const f=s(t,["addWatermark"]);if(e!==void 0&&f!=null){a(e,["parameters","addWatermark"],f)}const p=s(t,["outputMimeType"]);if(e!==void 0&&p!=null){a(e,["parameters","outputOptions","mimeType"],p)}const h=s(t,["outputCompressionQuality"]);if(e!==void 0&&h!=null){a(e,["parameters","outputOptions","compressionQuality"],h)}const m=s(t,["enhancePrompt"]);if(e!==void 0&&m!=null){a(e,["parameters","enhancePrompt"],m)}const _=s(t,["labels"]);if(e!==void 0&&_!=null){a(e,["labels"],_)}return i}function OA(t,e,n){const i={};const r=s(e,["model"]);if(r!=null){a(i,["_url","model"],j(t,r))}const o=s(e,["source"]);if(o!=null){FA(o,i)}const l=s(e,["config"]);if(l!=null){GA(l,i)}return i}function bA(t,e){const n={};const i=s(t,["predictions"]);if(i!=null){let r=i;if(Array.isArray(r)){r=r.map(o=>{return mr(o)})}a(n,["generatedImages"],r)}return n}function FA(t,e,n){const i={};const r=s(t,["prompt"]);if(e!==void 0&&r!=null){a(e,["instances[0]","prompt"],r)}const o=s(t,["personImage"]);if(e!==void 0&&o!=null){a(e,["instances[0]","personImage","image"],Ye(o))}const l=s(t,["productImages"]);if(e!==void 0&&l!=null){let u=l;if(Array.isArray(u)){u=u.map(c=>{return LA(c)})}a(e,["instances[0]","productImages"],u)}return i}function qA(t,e){const n={};const i=s(t,["referenceImage"]);if(i!=null){a(n,["referenceImage"],Ye(i))}const r=s(t,["referenceId"]);if(r!=null){a(n,["referenceId"],r)}const o=s(t,["referenceType"]);if(o!=null){a(n,["referenceType"],o)}const l=s(t,["maskImageConfig"]);if(l!=null){a(n,["maskImageConfig"],xA(l))}const u=s(t,["controlImageConfig"]);if(u!=null){a(n,["controlImageConfig"],IT(u))}const c=s(t,["styleImageConfig"]);if(c!=null){a(n,["styleImageConfig"],c)}const d=s(t,["subjectImageConfig"]);if(d!=null){a(n,["subjectImageConfig"],d)}return n}function kf(t,e){const n={};const i=s(t,["safetyAttributes","categories"]);if(i!=null){a(n,["categories"],i)}const r=s(t,["safetyAttributes","scores"]);if(r!=null){a(n,["scores"],r)}const o=s(t,["contentType"]);if(o!=null){a(n,["contentType"],o)}return n}function xf(t,e){const n={};const i=s(t,["safetyAttributes","categories"]);if(i!=null){a(n,["categories"],i)}const r=s(t,["safetyAttributes","scores"]);if(r!=null){a(n,["scores"],r)}const o=s(t,["contentType"]);if(o!=null){a(n,["contentType"],o)}return n}function HA(t,e){const n={};const i=s(t,["category"]);if(i!=null){a(n,["category"],i)}if(s(t,["method"])!==void 0){throw new Error("method parameter is not supported in Gemini API.")}const r=s(t,["threshold"]);if(r!=null){a(n,["threshold"],r)}return n}function VA(t,e){const n={};const i=s(t,["image"]);if(i!=null){a(n,["image"],Ye(i))}return n}function BA(t,e,n){const i={};const r=s(t,["mode"]);if(e!==void 0&&r!=null){a(e,["parameters","mode"],r)}const o=s(t,["maxPredictions"]);if(e!==void 0&&o!=null){a(e,["parameters","maxPredictions"],o)}const l=s(t,["confidenceThreshold"]);if(e!==void 0&&l!=null){a(e,["parameters","confidenceThreshold"],l)}const u=s(t,["maskDilation"]);if(e!==void 0&&u!=null){a(e,["parameters","maskDilation"],u)}const c=s(t,["binaryColorThreshold"]);if(e!==void 0&&c!=null){a(e,["parameters","binaryColorThreshold"],c)}const d=s(t,["labels"]);if(e!==void 0&&d!=null){a(e,["labels"],d)}return i}function $A(t,e,n){const i={};const r=s(e,["model"]);if(r!=null){a(i,["_url","model"],j(t,r))}const o=s(e,["source"]);if(o!=null){KA(o,i)}const l=s(e,["config"]);if(l!=null){BA(l,i)}return i}function JA(t,e){const n={};const i=s(t,["predictions"]);if(i!=null){let r=i;if(Array.isArray(r)){r=r.map(o=>{return gA(o)})}a(n,["generatedMasks"],r)}return n}function KA(t,e,n){const i={};const r=s(t,["prompt"]);if(e!==void 0&&r!=null){a(e,["instances[0]","prompt"],r)}const o=s(t,["image"]);if(e!==void 0&&o!=null){a(e,["instances[0]","image"],Ye(o))}const l=s(t,["scribbleImage"]);if(e!==void 0&&l!=null){a(e,["instances[0]","scribble"],VA(l))}return i}function WA(t,e){const n={};const i=s(t,["retrievalConfig"]);if(i!=null){a(n,["retrievalConfig"],i)}const r=s(t,["functionCallingConfig"]);if(r!=null){a(n,["functionCallingConfig"],YT(r))}const o=s(t,["includeServerSideToolInvocations"]);if(o!=null){a(n,["includeServerSideToolInvocations"],o)}return n}function YA(t,e){const n={};const i=s(t,["retrievalConfig"]);if(i!=null){a(n,["retrievalConfig"],i)}const r=s(t,["functionCallingConfig"]);if(r!=null){a(n,["functionCallingConfig"],r)}if(s(t,["includeServerSideToolInvocations"])!==void 0){throw new Error("includeServerSideToolInvocations parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).")}return n}function zA(t,e){const n={};if(s(t,["retrieval"])!==void 0){throw new Error("retrieval parameter is not supported in Gemini API.")}const i=s(t,["computerUse"]);if(i!=null){a(n,["computerUse"],i)}const r=s(t,["fileSearch"]);if(r!=null){a(n,["fileSearch"],r)}const o=s(t,["googleSearch"]);if(o!=null){a(n,["googleSearch"],CA(o))}const l=s(t,["googleMaps"]);if(l!=null){a(n,["googleMaps"],AA(l))}const u=s(t,["codeExecution"]);if(u!=null){a(n,["codeExecution"],u)}if(s(t,["enterpriseWebSearch"])!==void 0){throw new Error("enterpriseWebSearch parameter is not supported in Gemini API.")}const c=s(t,["functionDeclarations"]);if(c!=null){let h=c;if(Array.isArray(h)){h=h.map(m=>{return m})}a(n,["functionDeclarations"],h)}const d=s(t,["googleSearchRetrieval"]);if(d!=null){a(n,["googleSearchRetrieval"],d)}if(s(t,["parallelAiSearch"])!==void 0){throw new Error("parallelAiSearch parameter is not supported in Gemini API.")}const f=s(t,["urlContext"]);if(f!=null){a(n,["urlContext"],f)}const p=s(t,["mcpServers"]);if(p!=null){let h=p;if(Array.isArray(h)){h=h.map(m=>{return m})}a(n,["mcpServers"],h)}return n}function Df(t,e){const n={};const i=s(t,["retrieval"]);if(i!=null){a(n,["retrieval"],i)}const r=s(t,["computerUse"]);if(r!=null){a(n,["computerUse"],r)}if(s(t,["fileSearch"])!==void 0){throw new Error("fileSearch parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).")}const o=s(t,["googleSearch"]);if(o!=null){a(n,["googleSearch"],o)}const l=s(t,["googleMaps"]);if(l!=null){a(n,["googleMaps"],l)}const u=s(t,["codeExecution"]);if(u!=null){a(n,["codeExecution"],u)}const c=s(t,["enterpriseWebSearch"]);if(c!=null){a(n,["enterpriseWebSearch"],c)}const d=s(t,["functionDeclarations"]);if(d!=null){let m=d;if(Array.isArray(m)){m=m.map(_=>{return zT(_)})}a(n,["functionDeclarations"],m)}const f=s(t,["googleSearchRetrieval"]);if(f!=null){a(n,["googleSearchRetrieval"],f)}const p=s(t,["parallelAiSearch"]);if(p!=null){a(n,["parallelAiSearch"],p)}const h=s(t,["urlContext"]);if(h!=null){a(n,["urlContext"],h)}if(s(t,["mcpServers"])!==void 0){throw new Error("mcpServers parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).")}return n}function XA(t,e){const n={};const i=s(t,["baseModel"]);if(i!=null){a(n,["baseModel"],i)}const r=s(t,["createTime"]);if(r!=null){a(n,["createTime"],r)}const o=s(t,["updateTime"]);if(o!=null){a(n,["updateTime"],o)}return n}function QA(t,e){const n={};const i=s(t,["labels","google-vertex-llm-tuning-base-model-id"]);if(i!=null){a(n,["baseModel"],i)}const r=s(t,["createTime"]);if(r!=null){a(n,["createTime"],r)}const o=s(t,["updateTime"]);if(o!=null){a(n,["updateTime"],o)}return n}function ZA(t,e,n){const i={};const r=s(t,["displayName"]);if(e!==void 0&&r!=null){a(e,["displayName"],r)}const o=s(t,["description"]);if(e!==void 0&&o!=null){a(e,["description"],o)}const l=s(t,["defaultCheckpointId"]);if(e!==void 0&&l!=null){a(e,["defaultCheckpointId"],l)}return i}function jA(t,e,n){const i={};const r=s(t,["displayName"]);if(e!==void 0&&r!=null){a(e,["displayName"],r)}const o=s(t,["description"]);if(e!==void 0&&o!=null){a(e,["description"],o)}const l=s(t,["defaultCheckpointId"]);if(e!==void 0&&l!=null){a(e,["defaultCheckpointId"],l)}return i}function eC(t,e,n){const i={};const r=s(e,["model"]);if(r!=null){a(i,["_url","name"],j(t,r))}const o=s(e,["config"]);if(o!=null){ZA(o,i)}return i}function tC(t,e,n){const i={};const r=s(e,["model"]);if(r!=null){a(i,["_url","model"],j(t,r))}const o=s(e,["config"]);if(o!=null){jA(o,i)}return i}function nC(t,e,n){const i={};const r=s(t,["outputGcsUri"]);if(e!==void 0&&r!=null){a(e,["parameters","storageUri"],r)}const o=s(t,["safetyFilterLevel"]);if(e!==void 0&&o!=null){a(e,["parameters","safetySetting"],o)}const l=s(t,["personGeneration"]);if(e!==void 0&&l!=null){a(e,["parameters","personGeneration"],l)}const u=s(t,["includeRaiReason"]);if(e!==void 0&&u!=null){a(e,["parameters","includeRaiReason"],u)}const c=s(t,["outputMimeType"]);if(e!==void 0&&c!=null){a(e,["parameters","outputOptions","mimeType"],c)}const d=s(t,["outputCompressionQuality"]);if(e!==void 0&&d!=null){a(e,["parameters","outputOptions","compressionQuality"],d)}const f=s(t,["enhanceInputImage"]);if(e!==void 0&&f!=null){a(e,["parameters","upscaleConfig","enhanceInputImage"],f)}const p=s(t,["imagePreservationFactor"]);if(e!==void 0&&p!=null){a(e,["parameters","upscaleConfig","imagePreservationFactor"],p)}const h=s(t,["labels"]);if(e!==void 0&&h!=null){a(e,["labels"],h)}const m=s(t,["numberOfImages"]);if(e!==void 0&&m!=null){a(e,["parameters","sampleCount"],m)}const _=s(t,["mode"]);if(e!==void 0&&_!=null){a(e,["parameters","mode"],_)}return i}function iC(t,e,n){const i={};const r=s(e,["model"]);if(r!=null){a(i,["_url","model"],j(t,r))}const o=s(e,["image"]);if(o!=null){a(i,["instances[0]","image"],Ye(o))}const l=s(e,["upscaleFactor"]);if(l!=null){a(i,["parameters","upscaleConfig","upscaleFactor"],l)}const u=s(e,["config"]);if(u!=null){nC(u,i)}return i}function rC(t,e){const n={};const i=s(t,["sdkHttpResponse"]);if(i!=null){a(n,["sdkHttpResponse"],i)}const r=s(t,["predictions"]);if(r!=null){let o=r;if(Array.isArray(o)){o=o.map(l=>{return mr(l)})}a(n,["generatedImages"],o)}return n}function oC(t,e){const n={};const i=s(t,["uri"]);if(i!=null){a(n,["uri"],i)}const r=s(t,["encodedVideo"]);if(r!=null){a(n,["videoBytes"],Tt(r))}const o=s(t,["encoding"]);if(o!=null){a(n,["mimeType"],o)}return n}function sC(t,e){const n={};const i=s(t,["gcsUri"]);if(i!=null){a(n,["uri"],i)}const r=s(t,["bytesBase64Encoded"]);if(r!=null){a(n,["videoBytes"],Tt(r))}const o=s(t,["mimeType"]);if(o!=null){a(n,["mimeType"],o)}return n}function aC(t,e){const n={};const i=s(t,["image"]);if(i!=null){a(n,["_self"],Ye(i))}const r=s(t,["maskMode"]);if(r!=null){a(n,["maskMode"],r)}return n}function lC(t,e){const n={};const i=s(t,["image"]);if(i!=null){a(n,["image"],yr(i))}const r=s(t,["referenceType"]);if(r!=null){a(n,["referenceType"],r)}return n}function uC(t,e){const n={};const i=s(t,["image"]);if(i!=null){a(n,["image"],Ye(i))}const r=s(t,["referenceType"]);if(r!=null){a(n,["referenceType"],r)}return n}function Uf(t,e){const n={};const i=s(t,["uri"]);if(i!=null){a(n,["uri"],i)}const r=s(t,["videoBytes"]);if(r!=null){a(n,["encodedVideo"],Tt(r))}const o=s(t,["mimeType"]);if(o!=null){a(n,["encoding"],o)}return n}function Lf(t,e){const n={};const i=s(t,["uri"]);if(i!=null){a(n,["gcsUri"],i)}const r=s(t,["videoBytes"]);if(r!=null){a(n,["bytesBase64Encoded"],Tt(r))}const o=s(t,["mimeType"]);if(o!=null){a(n,["mimeType"],o)}return n}function cC(t,e,n){const i={};const r=s(e,["displayName"]);if(n!==void 0&&r!=null){a(n,["displayName"],r)}const o=s(e,["embeddingModel"]);if(n!==void 0&&o!=null){a(n,["embeddingModel"],j(t,o))}return i}function dC(t,e){const n={};const i=s(e,["config"]);if(i!=null){cC(t,i,n)}return n}function fC(t,e){const n={};const i=s(t,["force"]);if(e!==void 0&&i!=null){a(e,["_query","force"],i)}return n}function pC(t){const e={};const n=s(t,["name"]);if(n!=null){a(e,["_url","name"],n)}const i=s(t,["config"]);if(i!=null){fC(i,e)}return e}function hC(t){const e={};const n=s(t,["name"]);if(n!=null){a(e,["_url","name"],n)}return e}function gC(t,e){const n={};const i=s(t,["customMetadata"]);if(e!==void 0&&i!=null){let o=i;if(Array.isArray(o)){o=o.map(l=>{return l})}a(e,["customMetadata"],o)}const r=s(t,["chunkingConfig"]);if(e!==void 0&&r!=null){a(e,["chunkingConfig"],r)}return n}function mC(t){const e={};const n=s(t,["name"]);if(n!=null){a(e,["name"],n)}const i=s(t,["metadata"]);if(i!=null){a(e,["metadata"],i)}const r=s(t,["done"]);if(r!=null){a(e,["done"],r)}const o=s(t,["error"]);if(o!=null){a(e,["error"],o)}const l=s(t,["response"]);if(l!=null){a(e,["response"],EC(l))}return e}function yC(t){const e={};const n=s(t,["fileSearchStoreName"]);if(n!=null){a(e,["_url","file_search_store_name"],n)}const i=s(t,["fileName"]);if(i!=null){a(e,["fileName"],i)}const r=s(t,["config"]);if(r!=null){gC(r,e)}return e}function EC(t){const e={};const n=s(t,["sdkHttpResponse"]);if(n!=null){a(e,["sdkHttpResponse"],n)}const i=s(t,["parent"]);if(i!=null){a(e,["parent"],i)}const r=s(t,["documentName"]);if(r!=null){a(e,["documentName"],r)}return e}function _C(t,e){const n={};const i=s(t,["pageSize"]);if(e!==void 0&&i!=null){a(e,["_query","pageSize"],i)}const r=s(t,["pageToken"]);if(e!==void 0&&r!=null){a(e,["_query","pageToken"],r)}return n}function TC(t){const e={};const n=s(t,["config"]);if(n!=null){_C(n,e)}return e}function AC(t){const e={};const n=s(t,["sdkHttpResponse"]);if(n!=null){a(e,["sdkHttpResponse"],n)}const i=s(t,["nextPageToken"]);if(i!=null){a(e,["nextPageToken"],i)}const r=s(t,["fileSearchStores"]);if(r!=null){let o=r;if(Array.isArray(o)){o=o.map(l=>{return l})}a(e,["fileSearchStores"],o)}return e}function Gf(t,e){const n={};const i=s(t,["mimeType"]);if(e!==void 0&&i!=null){a(e,["mimeType"],i)}const r=s(t,["displayName"]);if(e!==void 0&&r!=null){a(e,["displayName"],r)}const o=s(t,["customMetadata"]);if(e!==void 0&&o!=null){let u=o;if(Array.isArray(u)){u=u.map(c=>{return c})}a(e,["customMetadata"],u)}const l=s(t,["chunkingConfig"]);if(e!==void 0&&l!=null){a(e,["chunkingConfig"],l)}return n}function CC(t){const e={};const n=s(t,["fileSearchStoreName"]);if(n!=null){a(e,["_url","file_search_store_name"],n)}const i=s(t,["config"]);if(i!=null){Gf(i,e)}return e}function vC(t){const e={};const n=s(t,["sdkHttpResponse"]);if(n!=null){a(e,["sdkHttpResponse"],n)}return e}var SC="Content-Type";var IC="X-Server-Timeout";var wC="User-Agent";var sa="x-goog-api-client";var RC="1.52.0";var PC=`google-genai-sdk/${RC}`;var NC="v1beta1";var MC="v1beta";var kC=new Set(["us","eu"]);var xC=5;var DC=[408,429,500,502,503,504];var aa=class{constructor(e){var n,i,r;this.clientOptions=Object.assign({},e);this.customBaseUrl=(n=e.httpOptions)===null||n===void 0?void 0:n.baseUrl;if(this.clientOptions.vertexai){if(this.clientOptions.project&&this.clientOptions.location){this.clientOptions.apiKey=void 0}else if(this.clientOptions.apiKey){this.clientOptions.project=void 0;this.clientOptions.location=void 0}}const o={};if(this.clientOptions.vertexai){if(!this.clientOptions.location&&!this.clientOptions.apiKey&&!this.customBaseUrl){this.clientOptions.location="global"}const l=this.clientOptions.project&&this.clientOptions.location||this.clientOptions.apiKey;if(!l&&!this.customBaseUrl){throw new Error("Authentication is not set up. Please provide either a project and location, or an API key, or a custom base URL.")}const u=e.project&&e.location||!!e.apiKey;if(this.customBaseUrl&&!u){o.baseUrl=this.customBaseUrl;this.clientOptions.project=void 0;this.clientOptions.location=void 0}else if(this.clientOptions.apiKey||this.clientOptions.location==="global"){o.baseUrl="https://aiplatform.googleapis.com/"}else if(this.clientOptions.project&&this.clientOptions.location&&kC.has(this.clientOptions.location)){o.baseUrl=`https://aiplatform.${this.clientOptions.location}.rep.googleapis.com/`}else if(this.clientOptions.project&&this.clientOptions.location){o.baseUrl=`https://${this.clientOptions.location}-aiplatform.googleapis.com/`}o.apiVersion=(i=this.clientOptions.apiVersion)!==null&&i!==void 0?i:NC}else{if(!this.clientOptions.apiKey){console.warn("API key should be set when using the Gemini API.")}o.apiVersion=(r=this.clientOptions.apiVersion)!==null&&r!==void 0?r:MC;o.baseUrl=`https://generativelanguage.googleapis.com/`}o.headers=this.getDefaultHeaders();this.clientOptions.httpOptions=o;if(e.httpOptions){this.clientOptions.httpOptions=this.patchHttpOptions(o,e.httpOptions)}}isVertexAI(){var e;return(e=this.clientOptions.vertexai)!==null&&e!==void 0?e:false}getProject(){return this.clientOptions.project}getLocation(){return this.clientOptions.location}getCustomBaseUrl(){return this.customBaseUrl}async getAuthHeaders(){const e=new Headers;await this.clientOptions.auth.addAuthHeaders(e);return e}getApiVersion(){if(this.clientOptions.httpOptions&&this.clientOptions.httpOptions.apiVersion!==void 0){return this.clientOptions.httpOptions.apiVersion}throw new Error("API version is not set.")}getBaseUrl(){if(this.clientOptions.httpOptions&&this.clientOptions.httpOptions.baseUrl!==void 0){return this.clientOptions.httpOptions.baseUrl}throw new Error("Base URL is not set.")}getRequestUrl(){return this.getRequestUrlInternal(this.clientOptions.httpOptions)}getHeaders(){if(this.clientOptions.httpOptions&&this.clientOptions.httpOptions.headers!==void 0){return this.clientOptions.httpOptions.headers}else{throw new Error("Headers are not set.")}}getRequestUrlInternal(e){if(!e||e.baseUrl===void 0||e.apiVersion===void 0){throw new Error("HTTP options are not correctly set.")}const n=e.baseUrl.endsWith("/")?e.baseUrl.slice(0,-1):e.baseUrl;const i=[n];if(e.apiVersion&&e.apiVersion!==""){i.push(e.apiVersion)}return i.join("/")}getBaseResourcePath(){return`projects/${this.clientOptions.project}/locations/${this.clientOptions.location}`}getApiKey(){return this.clientOptions.apiKey}getWebsocketBaseUrl(){const e=this.getBaseUrl();const n=new URL(e);n.protocol=n.protocol=="http:"?"ws":"wss";return n.toString()}setBaseUrl(e){if(this.clientOptions.httpOptions){this.clientOptions.httpOptions.baseUrl=e}else{throw new Error("HTTP options are not correctly set.")}}constructUrl(e,n,i){const r=[this.getRequestUrlInternal(n)];if(i){r.push(this.getBaseResourcePath())}if(e!==""){r.push(e)}const o=new URL(`${r.join("/")}`);return o}shouldPrependVertexProjectPath(e,n){if(n.baseUrl&&n.baseUrlResourceScope===Us.COLLECTION){return false}if(this.clientOptions.apiKey){return false}if(!this.clientOptions.vertexai){return false}if(e.path.startsWith("projects/")){return false}if(e.httpMethod==="GET"&&e.path.startsWith("publishers/google/models")){return false}return true}async request(e){let n=this.clientOptions.httpOptions;if(e.httpOptions){n=this.patchHttpOptions(this.clientOptions.httpOptions,e.httpOptions)}const i=this.shouldPrependVertexProjectPath(e,n);const r=this.constructUrl(e.path,n,i);if(e.queryParams){for(const[l,u]of Object.entries(e.queryParams)){r.searchParams.append(l,String(u))}}let o={};if(e.httpMethod==="GET"){if(e.body&&e.body!=="{}"){throw new Error("Request body should be empty for GET request, but got non empty request body")}}else{o.body=e.body}o=await this.includeExtraHttpOptionsToRequestInit(o,n,r.toString(),e.abortSignal);return this.unaryApiCall(r,o,e.httpMethod)}patchHttpOptions(e,n){const i=JSON.parse(JSON.stringify(e));for(const[r,o]of Object.entries(n)){if(typeof o==="object"){i[r]=Object.assign(Object.assign({},i[r]),o)}else if(o!==void 0){i[r]=o}}return i}async requestStream(e){let n=this.clientOptions.httpOptions;if(e.httpOptions){n=this.patchHttpOptions(this.clientOptions.httpOptions,e.httpOptions)}const i=this.shouldPrependVertexProjectPath(e,n);const r=this.constructUrl(e.path,n,i);if(!r.searchParams.has("alt")||r.searchParams.get("alt")!=="sse"){r.searchParams.set("alt","sse")}let o={};o.body=e.body;o=await this.includeExtraHttpOptionsToRequestInit(o,n,r.toString(),e.abortSignal);return this.streamApiCall(r,o,e.httpMethod)}async includeExtraHttpOptionsToRequestInit(e,n,i,r){if(n&&n.timeout||r){const o=new AbortController;const l=o.signal;if(n.timeout&&(n===null||n===void 0?void 0:n.timeout)>0){const u=setTimeout(()=>o.abort(),n.timeout);if(u&&typeof u.unref==="function"){u.unref()}}if(r){r.addEventListener("abort",()=>{o.abort()})}e.signal=l}if(n&&n.extraBody!==null){UC(e,n.extraBody)}e.headers=await this.getHeadersInternal(n,i);return e}async unaryApiCall(e,n,i){return this.apiCall(e.toString(),Object.assign(Object.assign({},n),{method:i})).then(async r=>{await Qd(r);return new _t(r)}).catch(r=>{if(r instanceof Error){throw r}else{throw new Error(JSON.stringify(r))}})}async streamApiCall(e,n,i){return this.apiCall(e.toString(),Object.assign(Object.assign({},n),{method:i})).then(async r=>{await Qd(r);return this.processStreamResponse(r)}).catch(r=>{if(r instanceof Error){throw r}else{throw new Error(JSON.stringify(r))}})}processStreamResponse(e){return Je(this,arguments,function*n(){var i;const r=(i=e===null||e===void 0?void 0:e.body)===null||i===void 0?void 0:i.getReader();const o=new TextDecoder("utf-8");if(!r){throw new Error("Response body is empty")}try{let l="";const u="data:";const c=["\n\n","\r\r","\r\n\r\n"];while(true){const{done:d,value:f}=yield X(r.read());if(d){if(l.trim().length>0){throw new Error("Incomplete JSON segment at the end")}break}const p=o.decode(f,{stream:true});try{const _=JSON.parse(p);if("error"in _){const A=JSON.parse(JSON.stringify(_["error"]));const T=A["status"];const v=A["code"];const G=`got status: ${T}. ${JSON.stringify(_)}`;if(v>=400&&v<600){const D=new Zi({message:G,status:v});throw D}}}catch(_){const A=_;if(A.name==="ApiError"){throw _}}l+=p;let h=-1;let m=0;while(true){h=-1;m=0;for(const T of c){const v=l.indexOf(T);if(v!==-1&&(h===-1||v<h)){h=v;m=T.length}}if(h===-1){break}const _=l.substring(0,h);l=l.substring(h+m);const A=_.trim();if(A.startsWith(u)){const T=A.substring(u.length).trim();try{const v=new Response(T,{headers:e===null||e===void 0?void 0:e.headers,status:e===null||e===void 0?void 0:e.status,statusText:e===null||e===void 0?void 0:e.statusText});yield yield X(new _t(v))}catch(v){throw new Error(`exception parsing stream chunk ${T}. ${v}`)}}}}}finally{r.releaseLock()}})}async apiCall(e,n){var i;if(!this.clientOptions.httpOptions||!this.clientOptions.httpOptions.retryOptions){return fetch(e,n)}const r=this.clientOptions.httpOptions.retryOptions;const o=async()=>{const l=await fetch(e,n);if(l.ok){return l}if(DC.includes(l.status)){throw new Error(`Retryable HTTP Error: ${l.statusText}`)}throw new hr.AbortError(`Non-retryable exception ${l.statusText} sending request`)};return(0,hr.default)(o,{retries:((i=r.attempts)!==null&&i!==void 0?i:xC)-1})}getDefaultHeaders(){const e={};const n=PC+" "+this.clientOptions.userAgentExtra;e[wC]=n;e[sa]=n;e[SC]="application/json";return e}async getHeadersInternal(e,n){const i=new Headers;if(e&&e.headers){for(const[r,o]of Object.entries(e.headers)){i.append(r,o)}if(e.timeout&&e.timeout>0){i.append(IC,String(Math.ceil(e.timeout/1e3)))}}await this.clientOptions.auth.addAuthHeaders(i,n);return i}getFileName(e){var n;let i="";if(typeof e==="string"){i=e.replace(/[/\\]+$/,"");i=(n=i.split(/[/\\]/).pop())!==null&&n!==void 0?n:""}return i}async uploadFile(e,n){var i;const r={};if(n!=null){r.mimeType=n.mimeType;r.name=n.name;r.displayName=n.displayName}if(r.name&&!r.name.startsWith("files/")){r.name=`files/${r.name}`}const o=this.clientOptions.uploader;const l=await o.stat(e);r.sizeBytes=String(l.size);const u=(i=n===null||n===void 0?void 0:n.mimeType)!==null&&i!==void 0?i:l.type;if(u===void 0||u===""){throw new Error("Can not determine mimeType. Please provide mimeType in the config.")}r.mimeType=u;const c={file:r};const d=this.getFileName(e);const f=H("upload/v1beta/files",c["_url"]);const p=await this.fetchUploadUrl(f,r.sizeBytes,r.mimeType,d,c,n===null||n===void 0?void 0:n.httpOptions);return o.upload(e,p,this)}async uploadFileToFileSearchStore(e,n,i){var r;const o=this.clientOptions.uploader;const l=await o.stat(n);const u=String(l.size);const c=(r=i===null||i===void 0?void 0:i.mimeType)!==null&&r!==void 0?r:l.type;if(c===void 0||c===""){throw new Error("Can not determine mimeType. Please provide mimeType in the config.")}const d=`upload/v1beta/${e}:uploadToFileSearchStore`;const f=this.getFileName(n);const p={};if(i!=null){Gf(i,p)}const h=await this.fetchUploadUrl(d,u,c,f,p,i===null||i===void 0?void 0:i.httpOptions);return o.uploadToFileSearchStore(n,h,this)}async downloadFile(e){const n=this.clientOptions.downloader;await n.download(e,this)}async fetchUploadUrl(e,n,i,r,o,l){var u;let c={};if(l){c=l}else{c={apiVersion:"",headers:Object.assign({"Content-Type":"application/json","X-Goog-Upload-Protocol":"resumable","X-Goog-Upload-Command":"start","X-Goog-Upload-Header-Content-Length":`${n}`,"X-Goog-Upload-Header-Content-Type":`${i}`},r?{"X-Goog-Upload-File-Name":r}:{})}}const d=await this.request({path:e,body:JSON.stringify(o),httpMethod:"POST",httpOptions:c});if(!d||!(d===null||d===void 0?void 0:d.headers)){throw new Error("Server did not return an HttpResponse or the returned HttpResponse did not have headers.")}const f=(u=d===null||d===void 0?void 0:d.headers)===null||u===void 0?void 0:u["x-goog-upload-url"];if(f===void 0){throw new Error("Failed to get upload url. Server did not return the x-google-upload-url in the headers")}return f}};async function Qd(t){var e;if(t===void 0){throw new Error("response is undefined")}if(!t.ok){const n=t.status;let i;if((e=t.headers.get("content-type"))===null||e===void 0?void 0:e.includes("application/json")){i=await t.json()}else{i={error:{message:await t.text(),code:t.status,status:t.statusText}}}const r=JSON.stringify(i);if(n>=400&&n<600){const o=new Zi({message:r,status:n});throw o}throw new Error(r)}}function UC(t,e){if(!e||Object.keys(e).length===0){return}if(t.body instanceof Blob){console.warn("includeExtraBodyToRequestInit: extraBody provided but current request body is a Blob. extraBody will be ignored as merging is not supported for Blob bodies.");return}let n={};if(typeof t.body==="string"&&t.body.length>0){try{const o=JSON.parse(t.body);if(typeof o==="object"&&o!==null&&!Array.isArray(o)){n=o}else{console.warn("includeExtraBodyToRequestInit: Original request body is valid JSON but not a non-array object. Skip applying extraBody to the request body.");return}}catch(o){console.warn("includeExtraBodyToRequestInit: Original request body is not valid JSON. Skip applying extraBody to the request body.");return}}function i(o,l){const u=Object.assign({},o);for(const c in l){if(Object.prototype.hasOwnProperty.call(l,c)){const d=l[c];const f=u[c];if(d&&typeof d==="object"&&!Array.isArray(d)&&f&&typeof f==="object"&&!Array.isArray(f)){u[c]=i(f,d)}else{if(f&&d&&typeof f!==typeof d){console.warn(`includeExtraBodyToRequestInit:deepMerge: Type mismatch for key "${c}". Original type: ${typeof f}, New type: ${typeof d}. Overwriting.`)}u[c]=d}}}return u}const r=i(n,e);t.body=JSON.stringify(r)}var LC="mcp_used/unknown";var GC=false;function Of(t){for(const e of t){if(OC(e)){return true}if(typeof e==="object"&&"inputSchema"in e){return true}}return GC}function bf(t){var e;const n=(e=t[sa])!==null&&e!==void 0?e:"";t[sa]=(n+` ${LC}`).trimStart()}function OC(t){return t!==null&&typeof t==="object"&&t instanceof la}function bC(t){return Je(this,arguments,function*e(n,i=100){let r=void 0;let o=0;while(o<i){const l=yield X(n.listTools({cursor:r}));for(const u of l.tools){yield yield X(u);o++}if(!l.nextCursor){break}r=l.nextCursor}})}var la=class t{constructor(e=[],n){this.mcpTools=[];this.functionNameToMcpClient={};this.mcpClients=e;this.config=n}static create(e,n){return new t(e,n)}async initialize(){var e,n,i,r;if(this.mcpTools.length>0){return}const o={};const l=[];for(const f of this.mcpClients){try{for(var u=true,c=(n=void 0,Ke(bC(f))),d;d=await c.next(),e=d.done,!e;u=true){r=d.value;u=false;const p=r;l.push(p);const h=p.name;if(o[h]){throw new Error(`Duplicate function name ${h} found in MCP tools. Please ensure function names are unique.`)}o[h]=f}}catch(p){n={error:p}}finally{try{if(!u&&!e&&(i=c.return))await i.call(c)}finally{if(n)throw n.error}}}this.mcpTools=l;this.functionNameToMcpClient=o}async tool(){await this.initialize();return nE(this.mcpTools,this.config)}async callTool(e){await this.initialize();const n=[];for(const i of e){if(i.name in this.functionNameToMcpClient){const r=this.functionNameToMcpClient[i.name];let o=void 0;if(this.config.timeout){o={timeout:this.config.timeout}}const l=await r.callTool({name:i.name,arguments:i.args},void 0,o);n.push({functionResponse:{name:i.name,response:l.isError?{error:l}:l}})}}return n}};async function FC(t,e,n){const i=new Xs;let r;if(n.data instanceof Blob){r=JSON.parse(await n.data.text())}else{r=JSON.parse(n.data)}Object.assign(i,r);e(i)}var ua=class{constructor(e,n,i){this.apiClient=e;this.auth=n;this.webSocketFactory=i}async connect(e){var n,i;if(this.apiClient.isVertexAI()){throw new Error("Live music is not supported for Vertex AI.")}console.warn("Live music generation is experimental and may change in future versions.");const r=this.apiClient.getWebsocketBaseUrl();const o=this.apiClient.getApiVersion();const l=HC(this.apiClient.getDefaultHeaders());const u=this.apiClient.getApiKey();const c=`${r}/ws/google.ai.generativelanguage.${o}.GenerativeService.BidiGenerateMusic?key=${u}`;let d=()=>{};const f=new Promise(D=>{d=D});const p=e.callbacks;const h=function(){d({})};const m=this.apiClient;const _={onopen:h,onmessage:D=>{void FC(m,p.onmessage,D)},onerror:(n=p===null||p===void 0?void 0:p.onerror)!==null&&n!==void 0?n:function(D){},onclose:(i=p===null||p===void 0?void 0:p.onclose)!==null&&i!==void 0?i:function(D){}};const A=this.webSocketFactory.create(c,qC(l),_);A.connect();await f;const T=j(this.apiClient,e.model);const v={model:T};const G={setup:v};A.send(JSON.stringify(G));return new ca(A,this.apiClient)}};var ca=class{constructor(e,n){this.conn=e;this.apiClient=n}async setWeightedPrompts(e){if(!e.weightedPrompts||Object.keys(e.weightedPrompts).length===0){throw new Error("Weighted prompts must be set and contain at least one entry.")}const n=oT(e);this.conn.send(JSON.stringify({clientContent:n}))}async setMusicGenerationConfig(e){if(!e.musicGenerationConfig){e.musicGenerationConfig={}}const n=rT(e);this.conn.send(JSON.stringify(n))}sendPlaybackControl(e){const n={playbackControl:e};this.conn.send(JSON.stringify(n))}play(){this.sendPlaybackControl(Xt.PLAY)}pause(){this.sendPlaybackControl(Xt.PAUSE)}stop(){this.sendPlaybackControl(Xt.STOP)}resetContext(){this.sendPlaybackControl(Xt.RESET_CONTEXT)}close(){this.conn.close()}};function qC(t){const e={};t.forEach((n,i)=>{e[i]=n});return e}function HC(t){const e=new Headers;for(const[n,i]of Object.entries(t)){e.append(n,i)}return e}var VC="FunctionResponse request must have an `id` field from the response of a ToolCall.FunctionalCalls in Google AI.";async function BC(t,e,n){const i=new zs;let r;if(n.data instanceof Blob){r=await n.data.text()}else if(n.data instanceof ArrayBuffer){r=new TextDecoder().decode(n.data)}else{r=n.data}const o=JSON.parse(r);if(t.isVertexAI()){const l=lT(o);Object.assign(i,l)}else{const l=o;Object.assign(i,l)}e(i)}var da=class{constructor(e,n,i){this.apiClient=e;this.auth=n;this.webSocketFactory=i;this.music=new ua(this.apiClient,this.auth,this.webSocketFactory)}async connect(e){var n,i,r,o,l,u;if(e.config&&e.config.httpOptions){throw new Error("The Live module does not support httpOptions at request-level in LiveConnectConfig yet. Please use the client-level httpOptions configuration instead.")}const c=this.apiClient.getWebsocketBaseUrl();const d=this.apiClient.getApiVersion();let f;const p=this.apiClient.getHeaders();if(e.config&&e.config.tools&&Of(e.config.tools)){bf(p)}const h=KC(p);if(this.apiClient.isVertexAI()){const k=this.apiClient.getProject();const $=this.apiClient.getLocation();const Y=this.apiClient.getApiKey();const Q=!!k&&!!$||!!Y;if(this.apiClient.getCustomBaseUrl()&&!Q){f=c}else{f=`${c}/ws/google.cloud.aiplatform.${d}.LlmBidiService/BidiGenerateContent`;await this.auth.addAuthHeaders(h,f)}}else{const k=this.apiClient.getApiKey();let $="BidiGenerateContent";let Y="key";if(k===null||k===void 0?void 0:k.startsWith("auth_tokens/")){console.warn("Warning: Ephemeral token support is experimental and may change in future versions.");if(d!=="v1alpha"){console.warn("Warning: The SDK's ephemeral token support is in v1alpha only. Please use const ai = new GoogleGenAI({apiKey: token.name, httpOptions: { apiVersion: 'v1alpha' }}); before session connection.")}$="BidiGenerateContentConstrained";Y="access_token"}f=`${c}/ws/google.ai.generativelanguage.${d}.GenerativeService.${$}?${Y}=${k}`}let m=()=>{};const _=new Promise(k=>{m=k});const A=e.callbacks;const T=function(){var k;(k=A===null||A===void 0?void 0:A.onopen)===null||k===void 0?void 0:k.call(A);m({})};const v=this.apiClient;const G={onopen:T,onmessage:k=>{void BC(v,A.onmessage,k)},onerror:(n=A===null||A===void 0?void 0:A.onerror)!==null&&n!==void 0?n:function(k){},onclose:(i=A===null||A===void 0?void 0:A.onclose)!==null&&i!==void 0?i:function(k){}};const D=this.webSocketFactory.create(f,JC(h),G);D.connect();await _;let O=j(this.apiClient,e.model);if(this.apiClient.isVertexAI()&&O.startsWith("publishers/")){const k=this.apiClient.getProject();const $=this.apiClient.getLocation();if(k&&$){O=`projects/${k}/locations/${$}/`+O}}let L={};if(this.apiClient.isVertexAI()&&((r=e.config)===null||r===void 0?void 0:r.responseModalities)===void 0){if(e.config===void 0){e.config={responseModalities:[bi.AUDIO]}}else{e.config.responseModalities=[bi.AUDIO]}}if((o=e.config)===null||o===void 0?void 0:o.generationConfig){console.warn("Setting `LiveConnectConfig.generation_config` is deprecated, please set the fields on `LiveConnectConfig` directly. This will become an error in a future version (not before Q3 2025).")}const R=(u=(l=e.config)===null||l===void 0?void 0:l.tools)!==null&&u!==void 0?u:[];const q=[];for(const k of R){if(this.isCallableTool(k)){const $=k;q.push(await $.tool())}else{q.push(k)}}if(q.length>0){e.config.tools=q}const V={model:O,config:e.config,callbacks:e.callbacks};if(this.apiClient.isVertexAI()){L=iT(this.apiClient,V)}else{L=nT(this.apiClient,V)}delete L["config"];D.send(JSON.stringify(L));return new fa(D,this.apiClient)}isCallableTool(e){return"callTool"in e&&typeof e.callTool==="function"}};var $C={turnComplete:true};var fa=class{constructor(e,n){this.conn=e;this.apiClient=n}tLiveClientContent(e,n){if(n.turns!==null&&n.turns!==void 0){let i=[];try{i=Ae(n.turns);if(!e.isVertexAI()){i=i.map(r=>Nn(r))}}catch(r){throw new Error(`Failed to parse client content "turns", type: '${typeof n.turns}'`)}return{clientContent:{turns:i,turnComplete:n.turnComplete}}}return{clientContent:{turnComplete:n.turnComplete}}}tLiveClienttToolResponse(e,n){let i=[];if(n.functionResponses==null){throw new Error("functionResponses is required.")}if(!Array.isArray(n.functionResponses)){i=[n.functionResponses]}else{i=n.functionResponses}if(i.length===0){throw new Error("functionResponses is required.")}for(const o of i){if(typeof o!=="object"||o===null||!("name"in o)||!("response"in o)){throw new Error(`Could not parse function response, type '${typeof o}'.`)}if(!e.isVertexAI()&&!("id"in o)){throw new Error(VC)}}const r={toolResponse:{"functionResponses":i}};return r}sendClientContent(e){e=Object.assign(Object.assign({},$C),e);const n=this.tLiveClientContent(this.apiClient,e);this.conn.send(JSON.stringify(n))}sendRealtimeInput(e){let n={};if(this.apiClient.isVertexAI()){n={"realtimeInput":aT(e)}}else{n={"realtimeInput":sT(e)}}this.conn.send(JSON.stringify(n))}sendToolResponse(e){if(e.functionResponses==null){throw new Error("Tool response parameters are required.")}const n=this.tLiveClienttToolResponse(this.apiClient,e);this.conn.send(JSON.stringify(n))}close(){this.conn.close()}};function JC(t){const e={};t.forEach((n,i)=>{e[i]=n});return e}function KC(t){const e=new Headers;for(const[n,i]of Object.entries(t)){e.append(n,i)}return e}var Zd=10;function jd(t){var e,n,i;if((e=t===null||t===void 0?void 0:t.automaticFunctionCalling)===null||e===void 0?void 0:e.disable){return true}let r=false;for(const l of(n=t===null||t===void 0?void 0:t.tools)!==null&&n!==void 0?n:[]){if(Zt(l)){r=true;break}}if(!r){return true}const o=(i=t===null||t===void 0?void 0:t.automaticFunctionCalling)===null||i===void 0?void 0:i.maximumRemoteCalls;if(o&&(o<0||!Number.isInteger(o))||o==0){console.warn("Invalid maximumRemoteCalls value provided for automatic function calling. Disabled automatic function calling. Please provide a valid integer value greater than 0. maximumRemoteCalls provided:",o);return true}return false}function Zt(t){return"callTool"in t&&typeof t.callTool==="function"}function WC(t){var e,n,i;return(i=(n=(e=t.config)===null||e===void 0?void 0:e.tools)===null||n===void 0?void 0:n.some(r=>Zt(r)))!==null&&i!==void 0?i:false}function ef(t){var e;const n=[];if(!((e=t===null||t===void 0?void 0:t.config)===null||e===void 0?void 0:e.tools)){return n}t.config.tools.forEach((i,r)=>{if(Zt(i)){return}const o=i;if(o.functionDeclarations&&o.functionDeclarations.length>0){n.push(r)}});return n}function tf(t){var e;return!((e=t===null||t===void 0?void 0:t.automaticFunctionCalling)===null||e===void 0?void 0:e.ignoreCallHistory)}var pa=class extends We{constructor(e){super();this.apiClient=e;this.embedContent=async n=>{if(!this.apiClient.isVertexAI()){const r=n.model.includes("gemini-embedding-2");if(r){n.contents=Ae(n.contents)}return await this.embedContentInternal(n)}const i=n.model.includes("gemini")&&n.model!=="gemini-embedding-001"||n.model.includes("maas");if(i){const r=Ae(n.contents);if(r.length>1){throw new Error("The embedContent API for this model only supports one content at a time.")}const o=Object.assign(Object.assign({},n),{content:r[0],embeddingApiType:Fi.EMBED_CONTENT});return await this.embedContentInternal(o)}else{const r=Object.assign(Object.assign({},n),{embeddingApiType:Fi.PREDICT});return await this.embedContentInternal(r)}};this.generateContent=async n=>{var i,r,o,l,u;const c=await this.processParamsMaybeAddMcpUsage(n);this.maybeMoveToResponseJsonSchem(n);if(!WC(n)||jd(n.config)){return await this.generateContentInternal(c)}const d=ef(n);if(d.length>0){const A=d.map(T=>`tools[${T}]`).join(", ");throw new Error(`Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations is not yet supported. Incompatible tools found at ${A}.`)}let f;let p;const h=Ae(c.contents);const m=(o=(r=(i=c.config)===null||i===void 0?void 0:i.automaticFunctionCalling)===null||r===void 0?void 0:r.maximumRemoteCalls)!==null&&o!==void 0?o:Zd;let _=0;while(_<m){f=await this.generateContentInternal(c);if(!f.functionCalls||f.functionCalls.length===0){break}const A=f.candidates[0].content;const T=[];for(const v of(u=(l=n.config)===null||l===void 0?void 0:l.tools)!==null&&u!==void 0?u:[]){if(Zt(v)){const G=v;const D=await G.callTool(f.functionCalls);T.push(...D)}}_++;p={role:"user",parts:T};c.contents=Ae(c.contents);c.contents.push(A);c.contents.push(p);if(tf(c.config)){h.push(A);h.push(p)}}if(tf(c.config)){f.automaticFunctionCallingHistory=h}return f};this.generateContentStream=async n=>{var i,r,o,l,u;this.maybeMoveToResponseJsonSchem(n);if(jd(n.config)){const p=await this.processParamsMaybeAddMcpUsage(n);return await this.generateContentStreamInternal(p)}const c=ef(n);if(c.length>0){const p=c.map(h=>`tools[${h}]`).join(", ");throw new Error(`Incompatible tools found at ${p}. Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations" is not yet supported.`)}const d=(o=(r=(i=n===null||n===void 0?void 0:n.config)===null||i===void 0?void 0:i.toolConfig)===null||r===void 0?void 0:r.functionCallingConfig)===null||o===void 0?void 0:o.streamFunctionCallArguments;const f=(u=(l=n===null||n===void 0?void 0:n.config)===null||l===void 0?void 0:l.automaticFunctionCalling)===null||u===void 0?void 0:u.disable;if(d&&!f){throw new Error("Running in streaming mode with 'streamFunctionCallArguments' enabled, this feature is not compatible with automatic function calling (AFC). Please set 'config.automaticFunctionCalling.disable' to true to disable AFC or leave 'config.toolConfig.functionCallingConfig.streamFunctionCallArguments' to be undefined or set to false to disable streaming function call arguments feature.")}return await this.processAfcStream(n)};this.generateImages=async n=>{return await this.generateImagesInternal(n).then(i=>{var r;let o;const l=[];if(i===null||i===void 0?void 0:i.generatedImages){for(const c of i.generatedImages){if(c&&(c===null||c===void 0?void 0:c.safetyAttributes)&&((r=c===null||c===void 0?void 0:c.safetyAttributes)===null||r===void 0?void 0:r.contentType)==="Positive Prompt"){o=c===null||c===void 0?void 0:c.safetyAttributes}else{l.push(c)}}}let u;if(o){u={generatedImages:l,positivePromptSafetyAttributes:o,sdkHttpResponse:i.sdkHttpResponse}}else{u={generatedImages:l,sdkHttpResponse:i.sdkHttpResponse}}return u})};this.list=async n=>{var i;const r={queryBase:true};const o=Object.assign(Object.assign({},r),n===null||n===void 0?void 0:n.config);const l={config:o};if(this.apiClient.isVertexAI()){if(!l.config.queryBase){if((i=l.config)===null||i===void 0?void 0:i.filter){throw new Error("Filtering tuned models list for Gemini Enterprise Agent Platform (previously known as Vertex AI) is not currently supported")}else{l.config.filter="labels.tune-type:*"}}}return new at(st.PAGED_ITEM_MODELS,u=>this.listInternal(u),await this.listInternal(l),l)};this.editImage=async n=>{const i={model:n.model,prompt:n.prompt,referenceImages:[],config:n.config};if(n.referenceImages){if(n.referenceImages){i.referenceImages=n.referenceImages.map(r=>r.toReferenceImageAPI())}}return await this.editImageInternal(i)};this.upscaleImage=async n=>{let i={numberOfImages:1,mode:"upscale"};if(n.config){i=Object.assign(Object.assign({},i),n.config)}const r={model:n.model,image:n.image,upscaleFactor:n.upscaleFactor,config:i};return await this.upscaleImageInternal(r)};this.generateVideos=async n=>{var i,r,o,l,u,c;if((n.prompt||n.image||n.video)&&n.source){throw new Error("Source and prompt/image/video are mutually exclusive. Please only use source.")}if(!this.apiClient.isVertexAI()){if(((i=n.video)===null||i===void 0?void 0:i.uri)&&((r=n.video)===null||r===void 0?void 0:r.videoBytes)){n.video={uri:n.video.uri,mimeType:n.video.mimeType}}else if(((l=(o=n.source)===null||o===void 0?void 0:o.video)===null||l===void 0?void 0:l.uri)&&((c=(u=n.source)===null||u===void 0?void 0:u.video)===null||c===void 0?void 0:c.videoBytes)){n.source.video={uri:n.source.video.uri,mimeType:n.source.video.mimeType}}}return await this.generateVideosInternal(n)}}maybeMoveToResponseJsonSchem(e){if(e.config&&e.config.responseSchema){if(!e.config.responseJsonSchema){if(Object.keys(e.config.responseSchema).includes("$schema")){e.config.responseJsonSchema=e.config.responseSchema;delete e.config.responseSchema}}}return}async processParamsMaybeAddMcpUsage(e){var n,i,r;const o=(n=e.config)===null||n===void 0?void 0:n.tools;if(!o){return e}const l=await Promise.all(o.map(async c=>{if(Zt(c)){const d=c;return await d.tool()}return c}));const u={model:e.model,contents:e.contents,config:Object.assign(Object.assign({},e.config),{tools:l})};u.config.tools=l;if(e.config&&e.config.tools&&Of(e.config.tools)){const c=(r=(i=e.config.httpOptions)===null||i===void 0?void 0:i.headers)!==null&&r!==void 0?r:{};let d=Object.assign({},c);if(Object.keys(d).length===0){d=this.apiClient.getDefaultHeaders()}bf(d);u.config.httpOptions=Object.assign(Object.assign({},e.config.httpOptions),{headers:d})}return u}async initAfcToolsMap(e){var n,i,r;const o=new Map;for(const l of(i=(n=e.config)===null||n===void 0?void 0:n.tools)!==null&&i!==void 0?i:[]){if(Zt(l)){const u=l;const c=await u.tool();for(const d of(r=c.functionDeclarations)!==null&&r!==void 0?r:[]){if(!d.name){throw new Error("Function declaration name is required.")}if(o.has(d.name)){throw new Error(`Duplicate tool declaration name: ${d.name}`)}o.set(d.name,u)}}}return o}async processAfcStream(e){var n,i,r;const o=(r=(i=(n=e.config)===null||n===void 0?void 0:n.automaticFunctionCalling)===null||i===void 0?void 0:i.maximumRemoteCalls)!==null&&r!==void 0?r:Zd;let l=false;let u=0;const c=await this.initAfcToolsMap(e);return(function(d,f,p){return Je(this,arguments,function*(){var h,m,_,A;var T,v;while(u<o){if(l){u++;l=false}const L=yield X(d.processParamsMaybeAddMcpUsage(p));const R=yield X(d.generateContentStreamInternal(L));const q=[];const V=[];try{for(var G=true,D=(m=void 0,Ke(R)),O;O=yield X(D.next()),h=O.done,!h;G=true){A=O.value;G=false;const k=A;yield yield X(k);if(k.candidates&&((T=k.candidates[0])===null||T===void 0?void 0:T.content)){V.push(k.candidates[0].content);for(const $ of(v=k.candidates[0].content.parts)!==null&&v!==void 0?v:[]){if(u<o&&$.functionCall){if(!$.functionCall.name){throw new Error("Function call name was not returned by the model.")}if(!f.has($.functionCall.name)){throw new Error(`Automatic function calling was requested, but not all the tools the model used implement the CallableTool interface. Available tools: ${f.keys()}, mising tool: ${$.functionCall.name}`)}else{const Y=yield X(f.get($.functionCall.name).callTool([$.functionCall]));q.push(...Y)}}}}}}catch(k){m={error:k}}finally{try{if(!G&&!h&&(_=D.return))yield X(_.call(D))}finally{if(m)throw m.error}}if(q.length>0){l=true;const k=new Mt;k.candidates=[{content:{role:"user",parts:q}}];yield yield X(k);const $=[];$.push(...V);$.push({role:"user",parts:q});const Y=Ae(p.contents).concat($);p.contents=Y}else{break}}})})(this,c,e)}async generateContentInternal(e){var n,i,r,o;let l;let u="";let c={};if(this.apiClient.isVertexAI()){const d=Yd(this.apiClient,e);u=H("{model}:generateContent",d["_url"]);c=d["_query"];delete d["_url"];delete d["_query"];l=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>{return f.json().then(p=>{const h=p;h.sdkHttpResponse={headers:f.headers};return h})});return l.then(f=>{const p=Xd(f);const h=new Mt;Object.assign(h,p);return h})}else{const d=Wd(this.apiClient,e);u=H("{model}:generateContent",d["_url"]);c=d["_query"];delete d["_url"];delete d["_query"];l=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(r=e.config)===null||r===void 0?void 0:r.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>{return f.json().then(p=>{const h=p;h.sdkHttpResponse={headers:f.headers};return h})});return l.then(f=>{const p=zd(f);const h=new Mt;Object.assign(h,p);return h})}}async generateContentStreamInternal(e){var n,i,r,o;let l;let u="";let c={};if(this.apiClient.isVertexAI()){const d=Yd(this.apiClient,e);u=H("{model}:streamGenerateContent?alt=sse",d["_url"]);c=d["_query"];delete d["_url"];delete d["_query"];const f=this.apiClient;l=f.requestStream({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal});return l.then(function(p){return Je(this,arguments,function*(){var h,m,_,A;try{for(var T=true,v=Ke(p),G;G=yield X(v.next()),h=G.done,!h;T=true){A=G.value;T=false;const D=A;const O=Xd(yield X(D.json()),e);O["sdkHttpResponse"]={headers:D.headers};const L=new Mt;Object.assign(L,O);yield yield X(L)}}catch(D){m={error:D}}finally{try{if(!T&&!h&&(_=v.return))yield X(_.call(v))}finally{if(m)throw m.error}}})})}else{const d=Wd(this.apiClient,e);u=H("{model}:streamGenerateContent?alt=sse",d["_url"]);c=d["_query"];delete d["_url"];delete d["_query"];const f=this.apiClient;l=f.requestStream({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(r=e.config)===null||r===void 0?void 0:r.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal});return l.then(function(p){return Je(this,arguments,function*(){var h,m,_,A;try{for(var T=true,v=Ke(p),G;G=yield X(v.next()),h=G.done,!h;T=true){A=G.value;T=false;const D=A;const O=zd(yield X(D.json()),e);O["sdkHttpResponse"]={headers:D.headers};const L=new Mt;Object.assign(L,O);yield yield X(L)}}catch(D){m={error:D}}finally{try{if(!T&&!h&&(_=v.return))yield X(_.call(v))}finally{if(m)throw m.error}}})})}}async embedContentInternal(e){var n,i,r,o;let l;let u="";let c={};if(this.apiClient.isVertexAI()){const d=VT(this.apiClient,e,e);const f=rE(e.model)?"{model}:embedContent":"{model}:predict";u=H(f,d["_url"]);c=d["_query"];delete d["_url"];delete d["_query"];l=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(p=>{return p.json().then(h=>{const m=h;m.sdkHttpResponse={headers:p.headers};return m})});return l.then(p=>{const h=$T(p,e);const m=new qi;Object.assign(m,h);return m})}else{const d=HT(this.apiClient,e);u=H("{model}:batchEmbedContents",d["_url"]);c=d["_query"];delete d["_url"];delete d["_query"];l=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(r=e.config)===null||r===void 0?void 0:r.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>{return f.json().then(p=>{const h=p;h.sdkHttpResponse={headers:f.headers};return h})});return l.then(f=>{const p=BT(f);const h=new qi;Object.assign(h,p);return h})}}async generateImagesInternal(e){var n,i,r,o;let l;let u="";let c={};if(this.apiClient.isVertexAI()){const d=tA(this.apiClient,e);u=H("{model}:predict",d["_url"]);c=d["_query"];delete d["_url"];delete d["_query"];l=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>{return f.json().then(p=>{const h=p;h.sdkHttpResponse={headers:f.headers};return h})});return l.then(f=>{const p=iA(f);const h=new Hi;Object.assign(h,p);return h})}else{const d=eA(this.apiClient,e);u=H("{model}:predict",d["_url"]);c=d["_query"];delete d["_url"];delete d["_query"];l=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(r=e.config)===null||r===void 0?void 0:r.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>{return f.json().then(p=>{const h=p;h.sdkHttpResponse={headers:f.headers};return h})});return l.then(f=>{const p=nA(f);const h=new Hi;Object.assign(h,p);return h})}}async editImageInternal(e){var n,i;let r;let o="";let l={};if(this.apiClient.isVertexAI()){const u=OT(this.apiClient,e);o=H("{model}:predict",u["_url"]);l=u["_query"];delete u["_url"];delete u["_query"];r=this.apiClient.request({path:o,queryParams:l,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(c=>{return c.json().then(d=>{const f=d;f.sdkHttpResponse={headers:c.headers};return f})});return r.then(c=>{const d=bT(c);const f=new Ls;Object.assign(f,d);return f})}else{throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}}async upscaleImageInternal(e){var n,i;let r;let o="";let l={};if(this.apiClient.isVertexAI()){const u=iC(this.apiClient,e);o=H("{model}:predict",u["_url"]);l=u["_query"];delete u["_url"];delete u["_query"];r=this.apiClient.request({path:o,queryParams:l,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(c=>{return c.json().then(d=>{const f=d;f.sdkHttpResponse={headers:c.headers};return f})});return r.then(c=>{const d=rC(c);const f=new Gs;Object.assign(f,d);return f})}else{throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}}async recontextImage(e){var n,i;let r;let o="";let l={};if(this.apiClient.isVertexAI()){const u=OA(this.apiClient,e);o=H("{model}:predict",u["_url"]);l=u["_query"];delete u["_url"];delete u["_query"];r=this.apiClient.request({path:o,queryParams:l,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(c=>{return c.json()});return r.then(c=>{const d=bA(c);const f=new Os;Object.assign(f,d);return f})}else{throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}}async segmentImage(e){var n,i;let r;let o="";let l={};if(this.apiClient.isVertexAI()){const u=$A(this.apiClient,e);o=H("{model}:predict",u["_url"]);l=u["_query"];delete u["_url"];delete u["_query"];r=this.apiClient.request({path:o,queryParams:l,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(c=>{return c.json()});return r.then(c=>{const d=JA(c);const f=new bs;Object.assign(f,d);return f})}else{throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}}async get(e){var n,i,r,o;let l;let u="";let c={};if(this.apiClient.isVertexAI()){const d=TA(this.apiClient,e);u=H("{name}",d["_url"]);c=d["_query"];delete d["_url"];delete d["_query"];l=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>{return f.json()});return l.then(f=>{const p=oa(f);return p})}else{const d=_A(this.apiClient,e);u=H("{name}",d["_url"]);c=d["_query"];delete d["_url"];delete d["_query"];l=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(r=e.config)===null||r===void 0?void 0:r.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>{return f.json()});return l.then(f=>{const p=ra(f);return p})}}async listInternal(e){var n,i,r,o;let l;let u="";let c={};if(this.apiClient.isVertexAI()){const d=NA(this.apiClient,e);u=H("{models_url}",d["_url"]);c=d["_query"];delete d["_url"];delete d["_query"];l=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>{return f.json().then(p=>{const h=p;h.sdkHttpResponse={headers:f.headers};return h})});return l.then(f=>{const p=kA(f);const h=new Vi;Object.assign(h,p);return h})}else{const d=PA(this.apiClient,e);u=H("{models_url}",d["_url"]);c=d["_query"];delete d["_url"];delete d["_query"];l=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(r=e.config)===null||r===void 0?void 0:r.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>{return f.json().then(p=>{const h=p;h.sdkHttpResponse={headers:f.headers};return h})});return l.then(f=>{const p=MA(f);const h=new Vi;Object.assign(h,p);return h})}}async update(e){var n,i,r,o;let l;let u="";let c={};if(this.apiClient.isVertexAI()){const d=tC(this.apiClient,e);u=H("{model}",d["_url"]);c=d["_query"];delete d["_url"];delete d["_query"];l=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"PATCH",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>{return f.json()});return l.then(f=>{const p=oa(f);return p})}else{const d=eC(this.apiClient,e);u=H("{name}",d["_url"]);c=d["_query"];delete d["_url"];delete d["_query"];l=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"PATCH",httpOptions:(r=e.config)===null||r===void 0?void 0:r.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>{return f.json()});return l.then(f=>{const p=ra(f);return p})}}async delete(e){var n,i,r,o;let l;let u="";let c={};if(this.apiClient.isVertexAI()){const d=DT(this.apiClient,e);u=H("{name}",d["_url"]);c=d["_query"];delete d["_url"];delete d["_query"];l=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"DELETE",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>{return f.json().then(p=>{const h=p;h.sdkHttpResponse={headers:f.headers};return h})});return l.then(f=>{const p=LT(f);const h=new Bi;Object.assign(h,p);return h})}else{const d=xT(this.apiClient,e);u=H("{name}",d["_url"]);c=d["_query"];delete d["_url"];delete d["_query"];l=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"DELETE",httpOptions:(r=e.config)===null||r===void 0?void 0:r.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>{return f.json().then(p=>{const h=p;h.sdkHttpResponse={headers:f.headers};return h})});return l.then(f=>{const p=UT(f);const h=new Bi;Object.assign(h,p);return h})}}async countTokens(e){var n,i,r,o;let l;let u="";let c={};if(this.apiClient.isVertexAI()){const d=NT(this.apiClient,e);u=H("{model}:countTokens",d["_url"]);c=d["_query"];delete d["_url"];delete d["_query"];l=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>{return f.json().then(p=>{const h=p;h.sdkHttpResponse={headers:f.headers};return h})});return l.then(f=>{const p=kT(f);const h=new $i;Object.assign(h,p);return h})}else{const d=PT(this.apiClient,e);u=H("{model}:countTokens",d["_url"]);c=d["_query"];delete d["_url"];delete d["_query"];l=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(r=e.config)===null||r===void 0?void 0:r.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>{return f.json().then(p=>{const h=p;h.sdkHttpResponse={headers:f.headers};return h})});return l.then(f=>{const p=MT(f);const h=new $i;Object.assign(h,p);return h})}}async computeTokens(e){var n,i;let r;let o="";let l={};if(this.apiClient.isVertexAI()){const u=AT(this.apiClient,e);o=H("{model}:computeTokens",u["_url"]);l=u["_query"];delete u["_url"];delete u["_query"];r=this.apiClient.request({path:o,queryParams:l,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(c=>{return c.json().then(d=>{const f=d;f.sdkHttpResponse={headers:c.headers};return f})});return r.then(c=>{const d=CT(c);const f=new Fs;Object.assign(f,d);return f})}else{throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}}async generateVideosInternal(e){var n,i,r,o;let l;let u="";let c={};if(this.apiClient.isVertexAI()){const d=uA(this.apiClient,e);u=H("{model}:predictLongRunning",d["_url"]);c=d["_query"];delete d["_url"];delete d["_query"];l=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>{return f.json()});return l.then(f=>{const p=aA(f);const h=new Ji;Object.assign(h,p);return h})}else{const d=lA(this.apiClient,e);u=H("{model}:predictLongRunning",d["_url"]);c=d["_query"];delete d["_url"];delete d["_query"];l=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(r=e.config)===null||r===void 0?void 0:r.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>{return f.json()});return l.then(f=>{const p=sA(f);const h=new Ji;Object.assign(h,p);return h})}}};var ha=class extends We{constructor(e){super();this.apiClient=e}async getVideosOperation(e){const n=e.operation;const i=e.config;if(n.name===void 0||n.name===""){throw new Error("Operation name is required.")}if(this.apiClient.isVertexAI()){const r=n.name.split("/operations/")[0];let o=void 0;if(i&&"httpOptions"in i){o=i.httpOptions}const l=await this.fetchPredictVideosOperationInternal({operationName:n.name,resourceName:r,config:{httpOptions:o}});return n._fromAPIResponse({apiResponse:l,_isVertexAI:true})}else{const r=await this.getVideosOperationInternal({operationName:n.name,config:i});return n._fromAPIResponse({apiResponse:r,_isVertexAI:false})}}async get(e){const n=e.operation;const i=e.config;if(n.name===void 0||n.name===""){throw new Error("Operation name is required.")}if(this.apiClient.isVertexAI()){const r=n.name.split("/operations/")[0];let o=void 0;if(i&&"httpOptions"in i){o=i.httpOptions}const l=await this.fetchPredictVideosOperationInternal({operationName:n.name,resourceName:r,config:{httpOptions:o}});return n._fromAPIResponse({apiResponse:l,_isVertexAI:true})}else{const r=await this.getVideosOperationInternal({operationName:n.name,config:i});return n._fromAPIResponse({apiResponse:r,_isVertexAI:false})}}async getVideosOperationInternal(e){var n,i,r,o;let l;let u="";let c={};if(this.apiClient.isVertexAI()){const d=Jy(e);u=H("{operationName}",d["_url"]);c=d["_query"];delete d["_url"];delete d["_query"];l=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>{return f.json()});return l}else{const d=$y(e);u=H("{operationName}",d["_url"]);c=d["_query"];delete d["_url"];delete d["_query"];l=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(r=e.config)===null||r===void 0?void 0:r.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>{return f.json()});return l}}async fetchPredictVideosOperationInternal(e){var n,i;let r;let o="";let l={};if(this.apiClient.isVertexAI()){const u=Oy(e);o=H("{resourceName}:fetchPredictOperation",u["_url"]);l=u["_query"];delete u["_url"];delete u["_query"];r=this.apiClient.request({path:o,queryParams:l,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(c=>{return c.json()});return r}else{throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}}};function nf(t){const e={};if(s(t,["languageCodes"])!==void 0){throw new Error("languageCodes parameter is not supported in Gemini API.")}return e}function YC(t){const e={};const n=s(t,["apiKey"]);if(n!=null){a(e,["apiKey"],n)}if(s(t,["apiKeyConfig"])!==void 0){throw new Error("apiKeyConfig parameter is not supported in Gemini API.")}if(s(t,["authType"])!==void 0){throw new Error("authType parameter is not supported in Gemini API.")}if(s(t,["googleServiceAccountConfig"])!==void 0){throw new Error("googleServiceAccountConfig parameter is not supported in Gemini API.")}if(s(t,["httpBasicAuthConfig"])!==void 0){throw new Error("httpBasicAuthConfig parameter is not supported in Gemini API.")}if(s(t,["oauthConfig"])!==void 0){throw new Error("oauthConfig parameter is not supported in Gemini API.")}if(s(t,["oidcConfig"])!==void 0){throw new Error("oidcConfig parameter is not supported in Gemini API.")}return e}function zC(t){const e={};const n=s(t,["data"]);if(n!=null){a(e,["data"],n)}if(s(t,["displayName"])!==void 0){throw new Error("displayName parameter is not supported in Gemini API.")}const i=s(t,["mimeType"]);if(i!=null){a(e,["mimeType"],i)}return e}function XC(t){const e={};const n=s(t,["parts"]);if(n!=null){let r=n;if(Array.isArray(r)){r=r.map(o=>{return ov(o)})}a(e,["parts"],r)}const i=s(t,["role"]);if(i!=null){a(e,["role"],i)}return e}function QC(t,e,n){const i={};const r=s(e,["expireTime"]);if(n!==void 0&&r!=null){a(n,["expireTime"],r)}const o=s(e,["newSessionExpireTime"]);if(n!==void 0&&o!=null){a(n,["newSessionExpireTime"],o)}const l=s(e,["uses"]);if(n!==void 0&&l!=null){a(n,["uses"],l)}const u=s(e,["liveConnectConstraints"]);if(n!==void 0&&u!=null){a(n,["bidiGenerateContentSetup"],rv(t,u))}const c=s(e,["lockAdditionalFields"]);if(n!==void 0&&c!=null){a(n,["fieldMask"],c)}return i}function ZC(t,e){const n={};const i=s(e,["config"]);if(i!=null){a(n,["config"],QC(t,i,n))}return n}function jC(t){const e={};if(s(t,["displayName"])!==void 0){throw new Error("displayName parameter is not supported in Gemini API.")}const n=s(t,["fileUri"]);if(n!=null){a(e,["fileUri"],n)}const i=s(t,["mimeType"]);if(i!=null){a(e,["mimeType"],i)}return e}function ev(t){const e={};const n=s(t,["id"]);if(n!=null){a(e,["id"],n)}const i=s(t,["args"]);if(i!=null){a(e,["args"],i)}const r=s(t,["name"]);if(r!=null){a(e,["name"],r)}if(s(t,["partialArgs"])!==void 0){throw new Error("partialArgs parameter is not supported in Gemini API.")}if(s(t,["willContinue"])!==void 0){throw new Error("willContinue parameter is not supported in Gemini API.")}return e}function tv(t){const e={};const n=s(t,["authConfig"]);if(n!=null){a(e,["authConfig"],YC(n))}const i=s(t,["enableWidget"]);if(i!=null){a(e,["enableWidget"],i)}return e}function nv(t){const e={};const n=s(t,["searchTypes"]);if(n!=null){a(e,["searchTypes"],n)}if(s(t,["blockingConfidence"])!==void 0){throw new Error("blockingConfidence parameter is not supported in Gemini API.")}if(s(t,["excludeDomains"])!==void 0){throw new Error("excludeDomains parameter is not supported in Gemini API.")}const i=s(t,["timeRangeFilter"]);if(i!=null){a(e,["timeRangeFilter"],i)}return e}function iv(t,e){const n={};const i=s(t,["generationConfig"]);if(e!==void 0&&i!=null){a(e,["setup","generationConfig"],i)}const r=s(t,["responseModalities"]);if(e!==void 0&&r!=null){a(e,["setup","generationConfig","responseModalities"],r)}const o=s(t,["temperature"]);if(e!==void 0&&o!=null){a(e,["setup","generationConfig","temperature"],o)}const l=s(t,["topP"]);if(e!==void 0&&l!=null){a(e,["setup","generationConfig","topP"],l)}const u=s(t,["topK"]);if(e!==void 0&&u!=null){a(e,["setup","generationConfig","topK"],u)}const c=s(t,["maxOutputTokens"]);if(e!==void 0&&c!=null){a(e,["setup","generationConfig","maxOutputTokens"],c)}const d=s(t,["mediaResolution"]);if(e!==void 0&&d!=null){a(e,["setup","generationConfig","mediaResolution"],d)}const f=s(t,["seed"]);if(e!==void 0&&f!=null){a(e,["setup","generationConfig","seed"],f)}const p=s(t,["speechConfig"]);if(e!==void 0&&p!=null){a(e,["setup","generationConfig","speechConfig"],ba(p))}const h=s(t,["thinkingConfig"]);if(e!==void 0&&h!=null){a(e,["setup","generationConfig","thinkingConfig"],h)}const m=s(t,["enableAffectiveDialog"]);if(e!==void 0&&m!=null){a(e,["setup","generationConfig","enableAffectiveDialog"],m)}const _=s(t,["systemInstruction"]);if(e!==void 0&&_!=null){a(e,["setup","systemInstruction"],XC(he(_)))}const A=s(t,["tools"]);if(e!==void 0&&A!=null){let V=nn(A);if(Array.isArray(V)){V=V.map(k=>{return lv(tn(k))})}a(e,["setup","tools"],V)}const T=s(t,["sessionResumption"]);if(e!==void 0&&T!=null){a(e,["setup","sessionResumption"],av(T))}const v=s(t,["inputAudioTranscription"]);if(e!==void 0&&v!=null){a(e,["setup","inputAudioTranscription"],nf(v))}const G=s(t,["outputAudioTranscription"]);if(e!==void 0&&G!=null){a(e,["setup","outputAudioTranscription"],nf(G))}const D=s(t,["realtimeInputConfig"]);if(e!==void 0&&D!=null){a(e,["setup","realtimeInputConfig"],D)}const O=s(t,["contextWindowCompression"]);if(e!==void 0&&O!=null){a(e,["setup","contextWindowCompression"],O)}const L=s(t,["proactivity"]);if(e!==void 0&&L!=null){a(e,["setup","proactivity"],L)}if(s(t,["explicitVadSignal"])!==void 0){throw new Error("explicitVadSignal parameter is not supported in Gemini API.")}const R=s(t,["avatarConfig"]);if(e!==void 0&&R!=null){a(e,["setup","avatarConfig"],R)}const q=s(t,["safetySettings"]);if(e!==void 0&&q!=null){let V=q;if(Array.isArray(V)){V=V.map(k=>{return sv(k)})}a(e,["setup","safetySettings"],V)}return n}function rv(t,e){const n={};const i=s(e,["model"]);if(i!=null){a(n,["setup","model"],j(t,i))}const r=s(e,["config"]);if(r!=null){a(n,["config"],iv(r,n))}return n}function ov(t){const e={};const n=s(t,["mediaResolution"]);if(n!=null){a(e,["mediaResolution"],n)}const i=s(t,["codeExecutionResult"]);if(i!=null){a(e,["codeExecutionResult"],i)}const r=s(t,["executableCode"]);if(r!=null){a(e,["executableCode"],r)}const o=s(t,["fileData"]);if(o!=null){a(e,["fileData"],jC(o))}const l=s(t,["functionCall"]);if(l!=null){a(e,["functionCall"],ev(l))}const u=s(t,["functionResponse"]);if(u!=null){a(e,["functionResponse"],u)}const c=s(t,["inlineData"]);if(c!=null){a(e,["inlineData"],zC(c))}const d=s(t,["text"]);if(d!=null){a(e,["text"],d)}const f=s(t,["thought"]);if(f!=null){a(e,["thought"],f)}const p=s(t,["thoughtSignature"]);if(p!=null){a(e,["thoughtSignature"],p)}const h=s(t,["videoMetadata"]);if(h!=null){a(e,["videoMetadata"],h)}const m=s(t,["toolCall"]);if(m!=null){a(e,["toolCall"],m)}const _=s(t,["toolResponse"]);if(_!=null){a(e,["toolResponse"],_)}const A=s(t,["partMetadata"]);if(A!=null){a(e,["partMetadata"],A)}return e}function sv(t){const e={};const n=s(t,["category"]);if(n!=null){a(e,["category"],n)}if(s(t,["method"])!==void 0){throw new Error("method parameter is not supported in Gemini API.")}const i=s(t,["threshold"]);if(i!=null){a(e,["threshold"],i)}return e}function av(t){const e={};const n=s(t,["handle"]);if(n!=null){a(e,["handle"],n)}if(s(t,["transparent"])!==void 0){throw new Error("transparent parameter is not supported in Gemini API.")}return e}function lv(t){const e={};if(s(t,["retrieval"])!==void 0){throw new Error("retrieval parameter is not supported in Gemini API.")}const n=s(t,["computerUse"]);if(n!=null){a(e,["computerUse"],n)}const i=s(t,["fileSearch"]);if(i!=null){a(e,["fileSearch"],i)}const r=s(t,["googleSearch"]);if(r!=null){a(e,["googleSearch"],nv(r))}const o=s(t,["googleMaps"]);if(o!=null){a(e,["googleMaps"],tv(o))}const l=s(t,["codeExecution"]);if(l!=null){a(e,["codeExecution"],l)}if(s(t,["enterpriseWebSearch"])!==void 0){throw new Error("enterpriseWebSearch parameter is not supported in Gemini API.")}const u=s(t,["functionDeclarations"]);if(u!=null){let p=u;if(Array.isArray(p)){p=p.map(h=>{return h})}a(e,["functionDeclarations"],p)}const c=s(t,["googleSearchRetrieval"]);if(c!=null){a(e,["googleSearchRetrieval"],c)}if(s(t,["parallelAiSearch"])!==void 0){throw new Error("parallelAiSearch parameter is not supported in Gemini API.")}const d=s(t,["urlContext"]);if(d!=null){a(e,["urlContext"],d)}const f=s(t,["mcpServers"]);if(f!=null){let p=f;if(Array.isArray(p)){p=p.map(h=>{return h})}a(e,["mcpServers"],p)}return e}function uv(t){const e=[];for(const n in t){if(Object.prototype.hasOwnProperty.call(t,n)){const i=t[n];if(typeof i==="object"&&i!=null&&Object.keys(i).length>0){const r=Object.keys(i).map(o=>`${n}.${o}`);e.push(...r)}else{e.push(n)}}}return e.join(",")}function cv(t,e){let n=null;const i=t["bidiGenerateContentSetup"];if(typeof i==="object"&&i!==null&&"setup"in i){const o=i.setup;if(typeof o==="object"&&o!==null){t["bidiGenerateContentSetup"]=o;n=o}else{delete t["bidiGenerateContentSetup"]}}else if(i!==void 0){delete t["bidiGenerateContentSetup"]}const r=t["fieldMask"];if(n){const o=uv(n);if(Array.isArray(e===null||e===void 0?void 0:e.lockAdditionalFields)&&(e===null||e===void 0?void 0:e.lockAdditionalFields.length)===0){if(o){t["fieldMask"]=o}else{delete t["fieldMask"]}}else if((e===null||e===void 0?void 0:e.lockAdditionalFields)&&e.lockAdditionalFields.length>0&&r!==null&&Array.isArray(r)&&r.length>0){const l=["temperature","topK","topP","maxOutputTokens","responseModalities","seed","speechConfig"];let u=[];if(r.length>0){u=r.map(d=>{if(l.includes(d)){return`generationConfig.${d}`}return d})}const c=[];if(o){c.push(o)}if(u.length>0){c.push(...u)}if(c.length>0){t["fieldMask"]=c.join(",")}else{delete t["fieldMask"]}}else{delete t["fieldMask"]}}else{if(r!==null&&Array.isArray(r)&&r.length>0){t["fieldMask"]=r.join(",")}else{delete t["fieldMask"]}}return t}var ga=class extends We{constructor(e){super();this.apiClient=e}async create(e){var n,i;let r;let o="";let l={};if(this.apiClient.isVertexAI()){throw new Error("The client.tokens.create method is only supported by the Gemini Developer API.")}else{const u=ZC(this.apiClient,e);o=H("auth_tokens",u["_url"]);l=u["_query"];delete u["config"];delete u["_url"];delete u["_query"];const c=cv(u,e.config);r=this.apiClient.request({path:o,queryParams:l,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(d=>{return d.json()});return r.then(d=>{return d})}}};function dv(t,e){const n={};const i=s(t,["force"]);if(e!==void 0&&i!=null){a(e,["_query","force"],i)}return n}function fv(t){const e={};const n=s(t,["name"]);if(n!=null){a(e,["_url","name"],n)}const i=s(t,["config"]);if(i!=null){dv(i,e)}return e}function pv(t){const e={};const n=s(t,["name"]);if(n!=null){a(e,["_url","name"],n)}return e}function hv(t,e){const n={};const i=s(t,["pageSize"]);if(e!==void 0&&i!=null){a(e,["_query","pageSize"],i)}const r=s(t,["pageToken"]);if(e!==void 0&&r!=null){a(e,["_query","pageToken"],r)}return n}function gv(t){const e={};const n=s(t,["parent"]);if(n!=null){a(e,["_url","parent"],n)}const i=s(t,["config"]);if(i!=null){hv(i,e)}return e}function mv(t){const e={};const n=s(t,["sdkHttpResponse"]);if(n!=null){a(e,["sdkHttpResponse"],n)}const i=s(t,["nextPageToken"]);if(i!=null){a(e,["nextPageToken"],i)}const r=s(t,["documents"]);if(r!=null){let o=r;if(Array.isArray(o)){o=o.map(l=>{return l})}a(e,["documents"],o)}return e}var ma=class extends We{constructor(e){super();this.apiClient=e;this.list=async n=>{return new at(st.PAGED_ITEM_DOCUMENTS,i=>this.listInternal({parent:n.parent,config:i.config}),await this.listInternal(n),n)}}async get(e){var n,i;let r;let o="";let l={};if(this.apiClient.isVertexAI()){throw new Error("This method is only supported by the Gemini Developer API.")}else{const u=pv(e);o=H("{name}",u["_url"]);l=u["_query"];delete u["_url"];delete u["_query"];r=this.apiClient.request({path:o,queryParams:l,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(c=>{return c.json()});return r.then(c=>{return c})}}async delete(e){var n,i;let r="";let o={};if(this.apiClient.isVertexAI()){throw new Error("This method is only supported by the Gemini Developer API.")}else{const l=fv(e);r=H("{name}",l["_url"]);o=l["_query"];delete l["_url"];delete l["_query"];await this.apiClient.request({path:r,queryParams:o,body:JSON.stringify(l),httpMethod:"DELETE",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal})}}async listInternal(e){var n,i;let r;let o="";let l={};if(this.apiClient.isVertexAI()){throw new Error("This method is only supported by the Gemini Developer API.")}else{const u=gv(e);o=H("{parent}/documents",u["_url"]);l=u["_query"];delete u["_url"];delete u["_query"];r=this.apiClient.request({path:o,queryParams:l,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(c=>{return c.json()});return r.then(c=>{const d=mv(c);const f=new Hs;Object.assign(f,d);return f})}}};var ya=class extends We{constructor(e,n=new ma(e)){super();this.apiClient=e;this.documents=n;this.list=async(i={})=>{return new at(st.PAGED_ITEM_FILE_SEARCH_STORES,r=>this.listInternal(r),await this.listInternal(i),i)}}async uploadToFileSearchStore(e){if(this.apiClient.isVertexAI()){throw new Error("Gemini Enterprise Agent Platform (previously known as Vertex AI) does not support uploading files to a file search store.")}return this.apiClient.uploadFileToFileSearchStore(e.fileSearchStoreName,e.file,e.config)}async downloadMedia(e,n){if(this.apiClient.isVertexAI()){throw new Error("This method is only supported in the Gemini Developer client.")}const i=new URL(e,"http://dummy.com");let r=i.pathname;if(r.startsWith("/")){r=r.slice(1)}if(!r.includes("/media/")){throw new Error(`Invalid uri format: ${e}. Expected to contain /media/`)}const o={};i.searchParams.forEach((c,d)=>{o[d]=c});o["alt"]="media";const l=Object.assign({},n===null||n===void 0?void 0:n.httpOptions);const u=await this.apiClient.request({path:r,httpMethod:"GET",queryParams:o,httpOptions:l});if(u instanceof _t){const c=await u.responseInternal.arrayBuffer();return new Uint8Array(c)}else{throw new Error("Unexpected response type from downloadMedia")}}async create(e){var n,i;let r;let o="";let l={};if(this.apiClient.isVertexAI()){throw new Error("This method is only supported by the Gemini Developer API.")}else{const u=dC(this.apiClient,e);o=H("fileSearchStores",u["_url"]);l=u["_query"];delete u["_url"];delete u["_query"];r=this.apiClient.request({path:o,queryParams:l,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(c=>{return c.json()});return r.then(c=>{return c})}}async get(e){var n,i;let r;let o="";let l={};if(this.apiClient.isVertexAI()){throw new Error("This method is only supported by the Gemini Developer API.")}else{const u=hC(e);o=H("{name}",u["_url"]);l=u["_query"];delete u["_url"];delete u["_query"];r=this.apiClient.request({path:o,queryParams:l,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(c=>{return c.json()});return r.then(c=>{return c})}}async delete(e){var n,i;let r="";let o={};if(this.apiClient.isVertexAI()){throw new Error("This method is only supported by the Gemini Developer API.")}else{const l=pC(e);r=H("{name}",l["_url"]);o=l["_query"];delete l["_url"];delete l["_query"];await this.apiClient.request({path:r,queryParams:o,body:JSON.stringify(l),httpMethod:"DELETE",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal})}}async listInternal(e){var n,i;let r;let o="";let l={};if(this.apiClient.isVertexAI()){throw new Error("This method is only supported by the Gemini Developer API.")}else{const u=TC(e);o=H("fileSearchStores",u["_url"]);l=u["_query"];delete u["_url"];delete u["_query"];r=this.apiClient.request({path:o,queryParams:l,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(c=>{return c.json()});return r.then(c=>{const d=AC(c);const f=new Vs;Object.assign(f,d);return f})}}async uploadToFileSearchStoreInternal(e){var n,i;let r;let o="";let l={};if(this.apiClient.isVertexAI()){throw new Error("This method is only supported by the Gemini Developer API.")}else{const u=CC(e);o=H("upload/v1beta/{file_search_store_name}:uploadToFileSearchStore",u["_url"]);l=u["_query"];delete u["_url"];delete u["_query"];r=this.apiClient.request({path:o,queryParams:l,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(c=>{return c.json()});return r.then(c=>{const d=vC(c);const f=new Bs;Object.assign(f,d);return f})}}async importFile(e){var n,i;let r;let o="";let l={};if(this.apiClient.isVertexAI()){throw new Error("This method is only supported by the Gemini Developer API.")}else{const u=yC(e);o=H("{file_search_store_name}:importFile",u["_url"]);l=u["_query"];delete u["_url"];delete u["_query"];r=this.apiClient.request({path:o,queryParams:l,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(c=>{return c.json()});return r.then(c=>{const d=mC(c);const f=new $s;Object.assign(f,d);return f})}}};var Ff=function(){const{crypto:t}=globalThis;if(t===null||t===void 0?void 0:t.randomUUID){Ff=t.randomUUID.bind(t);return t.randomUUID()}const e=new Uint8Array(1);const n=t?()=>t.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,i=>(+i^n()&15>>+i/4).toString(16))};var yv=()=>Ff();function Ea(t){return typeof t==="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}var _a=t=>{if(t instanceof Error)return t;if(typeof t==="object"&&t!==null){try{if(Object.prototype.toString.call(t)==="[object Error]"){const e=new Error(t.message,t.cause?{cause:t.cause}:{});if(t.stack)e.stack=t.stack;if(t.cause&&!e.cause)e.cause=t.cause;if(t.name)e.name=t.name;return e}}catch(e){}try{return new Error(JSON.stringify(t))}catch(e){}}return new Error(t)};var Ce=class extends Error{};var ve=class t extends Ce{constructor(e,n,i,r){super(`${t.makeMessage(e,n,i)}`);this.status=e;this.headers=r;this.error=n}static makeMessage(e,n,i){const r=(n===null||n===void 0?void 0:n.message)?typeof n.message==="string"?n.message:JSON.stringify(n.message):n?JSON.stringify(n):i;if(e&&r){return`${e} ${r}`}if(e){return`${e} status code (no body)`}if(r){return r}return"(no status code or body)"}static generate(e,n,i,r){if(!e||!r){return new jt({message:i,cause:_a(n)})}const o=n;if(e===400){return new er(e,o,i,r)}if(e===401){return new tr(e,o,i,r)}if(e===403){return new nr(e,o,i,r)}if(e===404){return new ir(e,o,i,r)}if(e===409){return new rr(e,o,i,r)}if(e===422){return new or(e,o,i,r)}if(e===429){return new sr(e,o,i,r)}if(e>=500){return new ar(e,o,i,r)}return new t(e,o,i,r)}};var Rn=class extends ve{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}};var jt=class extends ve{constructor({message:e,cause:n}){super(void 0,void 0,e||"Connection error.",void 0);if(n)this.cause=n}};var ji=class extends jt{constructor({message:e}={}){super({message:e!==null&&e!==void 0?e:"Request timed out."})}};var er=class extends ve{};var tr=class extends ve{};var nr=class extends ve{};var ir=class extends ve{};var rr=class extends ve{};var or=class extends ve{};var sr=class extends ve{};var ar=class extends ve{};var Ev=/^[a-z][a-z0-9+.-]*:/i;var _v=t=>{return Ev.test(t)};var Ta=t=>(Ta=Array.isArray,Ta(t));var Tv=Ta;var Av=Tv;var rf=Av;function of(t){if(!t)return true;for(const e in t)return false;return true}function Cv(t,e){return Object.prototype.hasOwnProperty.call(t,e)}var vv=(t,e)=>{if(typeof e!=="number"||!Number.isInteger(e)){throw new Ce(`${t} must be an integer`)}if(e<0){throw new Ce(`${t} must be a positive integer`)}return e};var Sv=t=>{try{return JSON.parse(t)}catch(e){return void 0}};var Iv=t=>new Promise(e=>setTimeout(e,t));function wv(){if(typeof fetch!=="undefined"){return fetch}throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new GeminiNextGenAPIClient({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function qf(...t){const e=globalThis.ReadableStream;if(typeof e==="undefined"){throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`")}return new e(...t)}function Rv(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return qf({start(){},async pull(n){const{done:i,value:r}=await e.next();if(i){n.close()}else{n.enqueue(r)}},async cancel(){var n;await((n=e.return)===null||n===void 0?void 0:n.call(e))}})}function Hf(t){if(t[Symbol.asyncIterator])return t;const e=t.getReader();return{async next(){try{const n=await e.read();if(n===null||n===void 0?void 0:n.done)e.releaseLock();return n}catch(n){e.releaseLock();throw n}},async return(){const n=e.cancel();e.releaseLock();await n;return{done:true,value:void 0}},[Symbol.asyncIterator](){return this}}}async function Pv(t){var e,n;if(t===null||typeof t!=="object")return;if(t[Symbol.asyncIterator]){await((n=(e=t[Symbol.asyncIterator]()).return)===null||n===void 0?void 0:n.call(e));return}const i=t.getReader();const r=i.cancel();i.releaseLock();await r}var Nv=({headers:t,body:e})=>{return{bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)}};function Mv(t){return Object.entries(t).filter(([e,n])=>typeof n!=="undefined").map(([e,n])=>{if(typeof n==="string"||typeof n==="number"||typeof n==="boolean"){return`${encodeURIComponent(e)}=${encodeURIComponent(n)}`}if(n===null){return`${encodeURIComponent(e)}=`}throw new Ce(`Cannot stringify type ${typeof n}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}var kv="0.0.1";var Vf=()=>{var t;if(typeof File==="undefined"){const{process:e}=globalThis;const n=typeof((t=e===null||e===void 0?void 0:e.versions)===null||t===void 0?void 0:t.node)==="string"&&parseInt(e.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(n?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function Ns(t,e,n){Vf();return new File(t,e!==null&&e!==void 0?e:"unknown_file",n)}function xv(t){return(typeof t==="object"&&t!==null&&("name"in t&&t.name&&String(t.name)||"url"in t&&t.url&&String(t.url)||"filename"in t&&t.filename&&String(t.filename)||"path"in t&&t.path&&String(t.path))||"").split(/[\\/]/).pop()||void 0}var Dv=t=>t!=null&&typeof t==="object"&&typeof t[Symbol.asyncIterator]==="function";var Bf=t=>t!=null&&typeof t==="object"&&typeof t.size==="number"&&typeof t.type==="string"&&typeof t.text==="function"&&typeof t.slice==="function"&&typeof t.arrayBuffer==="function";var Uv=t=>t!=null&&typeof t==="object"&&typeof t.name==="string"&&typeof t.lastModified==="number"&&Bf(t);var Lv=t=>t!=null&&typeof t==="object"&&typeof t.url==="string"&&typeof t.blob==="function";async function Gv(t,e,n){Vf();t=await t;if(Uv(t)){if(t instanceof File){return t}return Ns([await t.arrayBuffer()],t.name)}if(Lv(t)){const r=await t.blob();e||(e=new URL(t.url).pathname.split(/[\\/]/).pop());return Ns(await Aa(r),e,n)}const i=await Aa(t);e||(e=xv(t));if(!(n===null||n===void 0?void 0:n.type)){const r=i.find(o=>typeof o==="object"&&"type"in o&&o.type);if(typeof r==="string"){n=Object.assign(Object.assign({},n),{type:r})}}return Ns(i,e,n)}async function Aa(t){var e,n,i,r;var o;let l=[];if(typeof t==="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer){l.push(t)}else if(Bf(t)){l.push(t instanceof Blob?t:await t.arrayBuffer())}else if(Dv(t)){try{for(var u=true,c=Ke(t),d;d=await c.next(),e=d.done,!e;u=true){r=d.value;u=false;const f=r;l.push(...await Aa(f))}}catch(f){n={error:f}}finally{try{if(!u&&!e&&(i=c.return))await i.call(c)}finally{if(n)throw n.error}}}else{const f=(o=t===null||t===void 0?void 0:t.constructor)===null||o===void 0?void 0:o.name;throw new Error(`Unexpected data type: ${typeof t}${f?`; constructor: ${f}`:""}${Ov(t)}`)}return l}function Ov(t){if(typeof t!=="object"||t===null)return"";const e=Object.getOwnPropertyNames(t);return`; props: [${e.map(n=>`"${n}"`).join(", ")}]`}var Pn=class{constructor(e){this._client=e}};Pn._key=[];function $f(t){return t.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var sf=Object.freeze(Object.create(null));var bv=(t=$f)=>(function e(n,...i){if(n.length===1)return n[0];let r=false;const o=[];const l=n.reduce((f,p,h)=>{var m,_,A;if(/[?#]/.test(p)){r=true}const T=i[h];let v=(r?encodeURIComponent:t)(""+T);if(h!==i.length&&(T==null||typeof T==="object"&&T.toString===((A=Object.getPrototypeOf((_=Object.getPrototypeOf((m=T.hasOwnProperty)!==null&&m!==void 0?m:sf))!==null&&_!==void 0?_:sf))===null||A===void 0?void 0:A.toString))){v=T+"";o.push({start:f.length+p.length,length:v.length,error:`Value of type ${Object.prototype.toString.call(T).slice(8,-1)} is not a valid path parameter`})}return f+p+(h===i.length?"":v)},"");const u=l.split(/[?#]/,1)[0];const c=/(^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi;let d;while((d=c.exec(u))!==null){const f=d[0].startsWith("/");const p=f?1:0;const h=f?d[0].slice(1):d[0];o.push({start:d.index+p,length:h.length,error:`Value "${h}" can't be safely passed as a path parameter`})}o.sort((f,p)=>f.start-p.start);if(o.length>0){let f=0;const p=o.reduce((h,m)=>{const _=" ".repeat(m.start-f);const A="^".repeat(m.length);f=m.start+m.length;return h+_+A},"");throw new Ce(`Path parameters result in path with invalid segments:
15
+ ${o.map(h=>h.error).join("\n")}
16
+ ${l}
17
+ ${p}`)}return l});var $e=bv($f);var lr=class extends Pn{create(e,n){var i;const{api_version:r=this._client.apiVersion}=e,o=mt(e,["api_version"]);if("model"in o&&"agent_config"in o){throw new Ce(`Invalid request: specified \`model\` and \`agent_config\`. If specifying \`model\`, use \`generation_config\`.`)}if("agent"in o&&"generation_config"in o){throw new Ce(`Invalid request: specified \`agent\` and \`generation_config\`. If specifying \`agent\`, use \`agent_config\`.`)}return this._client.post($e`/${r}/interactions`,Object.assign(Object.assign({body:o},n),{stream:(i=e.stream)!==null&&i!==void 0?i:false}))}delete(e,n={},i){const{api_version:r=this._client.apiVersion}=n!==null&&n!==void 0?n:{};return this._client.delete($e`/${r}/interactions/${e}`,i)}cancel(e,n={},i){const{api_version:r=this._client.apiVersion}=n!==null&&n!==void 0?n:{};return this._client.post($e`/${r}/interactions/${e}/cancel`,i)}get(e,n={},i){var r;const o=n!==null&&n!==void 0?n:{},{api_version:l=this._client.apiVersion}=o,u=mt(o,["api_version"]);return this._client.get($e`/${l}/interactions/${e}`,Object.assign(Object.assign({query:u},i),{stream:(r=n===null||n===void 0?void 0:n.stream)!==null&&r!==void 0?r:false}))}};lr._key=Object.freeze(["interactions"]);var ur=class extends lr{};var cr=class extends Pn{create(e,n){const{api_version:i=this._client.apiVersion}=e,r=mt(e,["api_version"]);return this._client.post($e`/${i}/webhooks`,Object.assign({body:r},n))}update(e,n={},i){const r=n!==null&&n!==void 0?n:{},{api_version:o=this._client.apiVersion,update_mask:l}=r,u=mt(r,["api_version","update_mask"]);return this._client.patch($e`/${o}/webhooks/${e}`,Object.assign({query:{update_mask:l},body:u},i))}list(e={},n){const i=e!==null&&e!==void 0?e:{},{api_version:r=this._client.apiVersion}=i,o=mt(i,["api_version"]);return this._client.get($e`/${r}/webhooks`,Object.assign({query:o},n))}delete(e,n={},i){const{api_version:r=this._client.apiVersion}=n!==null&&n!==void 0?n:{};return this._client.delete($e`/${r}/webhooks/${e}`,i)}get(e,n={},i){const{api_version:r=this._client.apiVersion}=n!==null&&n!==void 0?n:{};return this._client.get($e`/${r}/webhooks/${e}`,i)}ping(e,n=void 0,i){const{api_version:r=this._client.apiVersion,body:o}=n!==null&&n!==void 0?n:{};return this._client.post($e`/${r}/webhooks/${e}:ping`,Object.assign({body:o},i))}rotateSigningSecret(e,n={},i){const r=n!==null&&n!==void 0?n:{},{api_version:o=this._client.apiVersion}=r,l=mt(r,["api_version"]);return this._client.post($e`/${o}/webhooks/${e}:rotateSigningSecret`,Object.assign({body:l},i))}};cr._key=Object.freeze(["webhooks"]);var dr=class extends cr{};function Fv(t){let e=0;for(const r of t){e+=r.length}const n=new Uint8Array(e);let i=0;for(const r of t){n.set(r,i);i+=r.length}return n}var Di;function qa(t){let e;return(Di!==null&&Di!==void 0?Di:(e=new globalThis.TextEncoder,Di=e.encode.bind(e)))(t)}var Ui;function af(t){let e;return(Ui!==null&&Ui!==void 0?Ui:(e=new globalThis.TextDecoder,Ui=e.decode.bind(e)))(t)}var en=class{constructor(){this.buffer=new Uint8Array;this.carriageReturnIndex=null;this.searchIndex=0}decode(e){var n;if(e==null){return[]}const i=e instanceof ArrayBuffer?new Uint8Array(e):typeof e==="string"?qa(e):e;this.buffer=Fv([this.buffer,i]);const r=[];let o;while((o=qv(this.buffer,(n=this.carriageReturnIndex)!==null&&n!==void 0?n:this.searchIndex))!=null){if(o.carriage&&this.carriageReturnIndex==null){this.carriageReturnIndex=o.index;continue}if(this.carriageReturnIndex!=null&&(o.index!==this.carriageReturnIndex+1||o.carriage)){r.push(af(this.buffer.subarray(0,this.carriageReturnIndex-1)));this.buffer=this.buffer.subarray(this.carriageReturnIndex);this.carriageReturnIndex=null;this.searchIndex=0;continue}const l=this.carriageReturnIndex!==null?o.preceding-1:o.preceding;const u=af(this.buffer.subarray(0,l));r.push(u);this.buffer=this.buffer.subarray(o.index);this.carriageReturnIndex=null;this.searchIndex=0}this.searchIndex=Math.max(0,this.buffer.length-1);return r}flush(){if(!this.buffer.length){return[]}return this.decode("\n")}};en.NEWLINE_CHARS=new Set(["\n","\r"]);en.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function qv(t,e){const n=10;const i=13;const r=e!==null&&e!==void 0?e:0;const o=t.indexOf(n,r);const l=t.indexOf(i,r);if(o===-1&&l===-1){return null}let u;if(o!==-1&&l!==-1){u=Math.min(o,l)}else{u=o!==-1?o:l}if(t[u]===n){return{preceding:u,index:u+1,carriage:false}}return{preceding:u,index:u+1,carriage:true}}var fr={off:0,error:200,warn:300,info:400,debug:500};var lf=(t,e,n)=>{if(!t){return void 0}if(Cv(fr,t)){return t}Te(n).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(fr))}`);return void 0};function wn(){}function Li(t,e,n){if(!e||fr[t]>fr[n]){return wn}else{return e[t].bind(e)}}var Hv={error:wn,warn:wn,info:wn,debug:wn};var uf=new WeakMap;function Te(t){var e;const n=t.logger;const i=(e=t.logLevel)!==null&&e!==void 0?e:"off";if(!n){return Hv}const r=uf.get(n);if(r&&r[0]===i){return r[1]}const o={error:Li("error",n,i),warn:Li("warn",n,i),info:Li("info",n,i),debug:Li("debug",n,i)};uf.set(n,[i,o]);return o}var Nt=t=>{if(t.options){t.options=Object.assign({},t.options);delete t.options["headers"]}if(t.headers){t.headers=Object.fromEntries((t.headers instanceof Headers?[...t.headers]:Object.entries(t.headers)).map(([e,n])=>[e,e.toLowerCase()==="x-goog-api-key"||e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":n]))}if("retryOfRequestLogID"in t){if(t.retryOfRequestLogID){t.retryOf=t.retryOfRequestLogID}delete t.retryOfRequestLogID}return t};var Ca=class t{constructor(e,n,i){this.iterator=e;this.controller=n;this.client=i}static fromSSEResponse(e,n,i){let r=false;const o=i?Te(i):console;function l(){return Je(this,arguments,function*u(){var c,d,f,p;if(r){throw new Ce("Cannot iterate over a consumed stream, use `.tee()` to split the stream.")}r=true;let h=false;try{try{for(var m=true,_=Ke(Vv(e,n)),A;A=yield X(_.next()),c=A.done,!c;m=true){p=A.value;m=false;const T=p;if(h)continue;if(T.data.startsWith("[DONE]")){h=true;continue}else{try{yield yield X(JSON.parse(T.data))}catch(v){o.error(`Could not parse message into JSON:`,T.data);o.error(`From chunk:`,T.raw);throw v}}}}catch(T){d={error:T}}finally{try{if(!m&&!c&&(f=_.return))yield X(f.call(_))}finally{if(d)throw d.error}}h=true}catch(T){if(Ea(T))return yield X(void 0);throw T}finally{if(!h)n.abort()}})}return new t(l,n,i)}static fromReadableStream(e,n,i){let r=false;function o(){return Je(this,arguments,function*u(){var c,d,f,p;const h=new en;const m=Hf(e);try{for(var _=true,A=Ke(m),T;T=yield X(A.next()),c=T.done,!c;_=true){p=T.value;_=false;const v=p;for(const G of h.decode(v)){yield yield X(G)}}}catch(v){d={error:v}}finally{try{if(!_&&!c&&(f=A.return))yield X(f.call(A))}finally{if(d)throw d.error}}for(const v of h.flush()){yield yield X(v)}})}function l(){return Je(this,arguments,function*u(){var c,d,f,p;if(r){throw new Ce("Cannot iterate over a consumed stream, use `.tee()` to split the stream.")}r=true;let h=false;try{try{for(var m=true,_=Ke(o()),A;A=yield X(_.next()),c=A.done,!c;m=true){p=A.value;m=false;const T=p;if(h)continue;if(T)yield yield X(JSON.parse(T))}}catch(T){d={error:T}}finally{try{if(!m&&!c&&(f=_.return))yield X(f.call(_))}finally{if(d)throw d.error}}h=true}catch(T){if(Ea(T))return yield X(void 0);throw T}finally{if(!h)n.abort()}})}return new t(l,n,i)}[Symbol.asyncIterator](){return this.iterator()}tee(){const e=[];const n=[];const i=this.iterator();const r=o=>{return{next:()=>{if(o.length===0){const l=i.next();e.push(l);n.push(l)}return o.shift()}}};return[new t(()=>r(e),this.controller,this.client),new t(()=>r(n),this.controller,this.client)]}toReadableStream(){const e=this;let n;return qf({async start(){n=e[Symbol.asyncIterator]()},async pull(i){try{const{value:r,done:o}=await n.next();if(o)return i.close();const l=qa(JSON.stringify(r)+"\n");i.enqueue(l)}catch(r){i.error(r)}},async cancel(){var i;await((i=n.return)===null||i===void 0?void 0:i.call(n))}})}};function Vv(t,e){return Je(this,arguments,function*n(){var i,r,o,l;if(!t.body){e.abort();if(typeof globalThis.navigator!=="undefined"&&globalThis.navigator.product==="ReactNative"){throw new Ce(`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 Ce(`Attempted to iterate over a response with no body`)}const u=new va;const c=new en;const d=Hf(t.body);try{for(var f=true,p=Ke(Bv(d)),h;h=yield X(p.next()),i=h.done,!i;f=true){l=h.value;f=false;const m=l;for(const _ of c.decode(m)){const A=u.decode(_);if(A)yield yield X(A)}}}catch(m){r={error:m}}finally{try{if(!f&&!i&&(o=p.return))yield X(o.call(p))}finally{if(r)throw r.error}}for(const m of c.flush()){const _=u.decode(m);if(_)yield yield X(_)}})}function Bv(t){return Je(this,arguments,function*e(){var n,i,r,o;try{for(var l=true,u=Ke(t),c;c=yield X(u.next()),n=c.done,!n;l=true){o=c.value;l=false;const d=o;if(d==null){continue}const f=d instanceof ArrayBuffer?new Uint8Array(d):typeof d==="string"?qa(d):d;yield yield X(f)}}catch(d){i={error:d}}finally{try{if(!l&&!n&&(r=u.return))yield X(r.call(u))}finally{if(i)throw i.error}}})}var va=class{constructor(){this.event=null;this.data=[];this.chunks=[]}decode(e){if(e.endsWith("\r")){e=e.substring(0,e.length-1)}if(!e){if(!this.event&&!this.data.length)return null;const o={event:this.event,data:this.data.join("\n"),raw:this.chunks};this.event=null;this.data=[];this.chunks=[];return o}this.chunks.push(e);if(e.startsWith(":")){return null}let[n,i,r]=$v(e,":");if(r.startsWith(" ")){r=r.substring(1)}if(n==="event"){this.event=r}else if(n==="data"){this.data.push(r)}return null}};function $v(t,e){const n=t.indexOf(e);if(n!==-1){return[t.substring(0,n),e,t.substring(n+e.length)]}return[t,"",""]}async function Jv(t,e){const{response:n,requestLogID:i,retryOfRequestLogID:r,startTime:o}=e;const l=await(async()=>{var u;if(e.options.stream){Te(t).debug("response",n.status,n.url,n.headers,n.body);if(e.options.__streamClass){return e.options.__streamClass.fromSSEResponse(n,e.controller,t)}return Ca.fromSSEResponse(n,e.controller,t)}if(n.status===204){return null}if(e.options.__binaryResponse){return n}const c=n.headers.get("content-type");const d=(u=c===null||c===void 0?void 0:c.split(";")[0])===null||u===void 0?void 0:u.trim();const f=(d===null||d===void 0?void 0:d.includes("application/json"))||(d===null||d===void 0?void 0:d.endsWith("+json"));if(f){const h=n.headers.get("content-length");if(h==="0"){return void 0}const m=await n.json();return m}const p=await n.text();return p})();Te(t).debug(`[${i}] response parsed`,Nt({retryOfRequestLogID:r,url:n.url,status:n.status,body:l,durationMs:Date.now()-o}));return l}var Sa=class t extends Promise{constructor(e,n,i=Jv){super(r=>{r(null)});this.responsePromise=n;this.parseResponse=i;this.client=e}_thenUnwrap(e){return new t(this.client,this.responsePromise,async(n,i)=>e(await this.parseResponse(n,i),i))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){const[e,n]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:n}}parse(){if(!this.parsedPromise){this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(this.client,e))}return this.parsedPromise}then(e,n){return this.parse().then(e,n)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};var Jf=Symbol("brand.privateNullableHeaders");function*Kv(t){if(!t)return;if(Jf in t){const{values:i,nulls:r}=t;yield*i.entries();for(const o of r){yield[o,null]}return}let e=false;let n;if(t instanceof Headers){n=t.entries()}else if(rf(t)){n=t}else{e=true;n=Object.entries(t!==null&&t!==void 0?t:{})}for(let i of n){const r=i[0];if(typeof r!=="string")throw new TypeError("expected header name to be a string");const o=rf(i[1])?i[1]:[i[1]];let l=false;for(const u of o){if(u===void 0)continue;if(e&&!l){l=true;yield[r,null]}yield[r,u]}}}var Sn=t=>{const e=new Headers;const n=new Set;for(const i of t){const r=new Set;for(const[o,l]of Kv(i)){const u=o.toLowerCase();if(!r.has(u)){e.delete(o);r.add(u)}if(l===null){e.delete(o);n.add(u)}else{e.append(o,l);n.delete(u)}}}return{[Jf]:true,values:e,nulls:n}};var Ms=t=>{var e,n,i,r,o;if(typeof globalThis.process!=="undefined"){return((n=(e=globalThis.process.env)===null||e===void 0?void 0:e[t])===null||n===void 0?void 0:n.trim())||void 0}if(typeof globalThis.Deno!=="undefined"){return((o=(r=(i=globalThis.Deno.env)===null||i===void 0?void 0:i.get)===null||r===void 0?void 0:r.call(i,t))===null||o===void 0?void 0:o.trim())||void 0}return void 0};var Kf;var pr=class t{constructor(e){var n,i,r,o,l,u,c;var{baseURL:d=Ms("GEMINI_NEXT_GEN_API_BASE_URL"),apiKey:f=(n=Ms("GEMINI_API_KEY"))!==null&&n!==void 0?n:null,apiVersion:p="v1beta"}=e,h=mt(e,["baseURL","apiKey","apiVersion"]);const m=Object.assign(Object.assign({apiKey:f,apiVersion:p},h),{baseURL:d||`https://generativelanguage.googleapis.com`});this.baseURL=m.baseURL;this.timeout=(i=m.timeout)!==null&&i!==void 0?i:t.DEFAULT_TIMEOUT;this.logger=(r=m.logger)!==null&&r!==void 0?r:console;const _="warn";this.logLevel=_;this.logLevel=(l=(o=lf(m.logLevel,"ClientOptions.logLevel",this))!==null&&o!==void 0?o:lf(Ms("GEMINI_NEXT_GEN_API_LOG"),"process.env['GEMINI_NEXT_GEN_API_LOG']",this))!==null&&l!==void 0?l:_;this.fetchOptions=m.fetchOptions;this.maxRetries=(u=m.maxRetries)!==null&&u!==void 0?u:2;this.fetch=(c=m.fetch)!==null&&c!==void 0?c:wv();this.encoder=Nv;this._options=m;this.apiKey=f;this.apiVersion=p;this.clientAdapter=m.clientAdapter}withOptions(e){const n=new this.constructor(Object.assign(Object.assign(Object.assign({},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,apiVersion:this.apiVersion}),e));return n}baseURLOverridden(){return this.baseURL!=="https://generativelanguage.googleapis.com"}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:n}){if(e.has("authorization")||e.has("x-goog-api-key")){return}if(this.apiKey&&e.get("x-goog-api-key")){return}if(n.has("x-goog-api-key")){return}throw new Error('Could not resolve authentication method. Expected the apiKey to be set. Or for the "x-goog-api-key" headers to be explicitly omitted')}async authHeaders(e){const n=Sn([e.headers]);if(n.values.has("authorization")||n.values.has("x-goog-api-key")){return void 0}if(this.apiKey){return Sn([{"x-goog-api-key":this.apiKey}])}if(this.clientAdapter&&this.clientAdapter.isVertexAI()){return Sn([await this.clientAdapter.getAuthHeaders()])}return void 0}stringifyQuery(e){return Mv(e)}getUserAgent(){return`${this.constructor.name}/JS ${kv}`}defaultIdempotencyKey(){return`stainless-node-retry-${yv()}`}makeStatusError(e,n,i,r){return ve.generate(e,n,i,r)}buildURL(e,n,i){const r=!this.baseURLOverridden()&&i||this.baseURL;const o=_v(e)?new URL(e):new URL(r+(r.endsWith("/")&&e.startsWith("/")?e.slice(1):e));const l=this.defaultQuery();const u=Object.fromEntries(o.searchParams);if(!of(l)||!of(u)){n=Object.assign(Object.assign(Object.assign({},u),l),n)}if(typeof n==="object"&&n&&!Array.isArray(n)){o.search=this.stringifyQuery(n)}return o.toString()}async prepareOptions(e){if(this.clientAdapter&&this.clientAdapter.isVertexAI()&&!e.path.startsWith(`/${this.apiVersion}/projects/`)){const n=e.path.slice(this.apiVersion.length+1);e.path=`/${this.apiVersion}/projects/${this.clientAdapter.getProject()}/locations/${this.clientAdapter.getLocation()}${n}`}}async prepareRequest(e,{url:n,options:i}){}get(e,n){return this.methodRequest("get",e,n)}post(e,n){return this.methodRequest("post",e,n)}patch(e,n){return this.methodRequest("patch",e,n)}put(e,n){return this.methodRequest("put",e,n)}delete(e,n){return this.methodRequest("delete",e,n)}methodRequest(e,n,i){return this.request(Promise.resolve(i).then(r=>{return Object.assign({method:e,path:n},r)}))}request(e,n=null){return new Sa(this,this.makeRequest(e,n,void 0))}async makeRequest(e,n,i){var r,o,l;const u=await e;const c=(r=u.maxRetries)!==null&&r!==void 0?r:this.maxRetries;if(n==null){n=c}await this.prepareOptions(u);const{req:d,url:f,timeout:p}=await this.buildRequest(u,{retryCount:c-n});await this.prepareRequest(d,{url:f,options:u});const h="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0");const m=i===void 0?"":`, retryOf: ${i}`;const _=Date.now();Te(this).debug(`[${h}] sending request`,Nt({retryOfRequestLogID:i,method:u.method,url:f,options:u,headers:d.headers}));if((o=u.signal)===null||o===void 0?void 0:o.aborted){throw new Rn}const A=new AbortController;const T=await this.fetchWithTimeout(f,d,p,A).catch(_a);const v=Date.now();if(T instanceof globalThis.Error){const D=`retrying, ${n} attempts remaining`;if((l=u.signal)===null||l===void 0?void 0:l.aborted){throw new Rn}const O=Ea(T)||/timed? ?out/i.test(String(T)+("cause"in T?String(T.cause):""));if(n){Te(this).info(`[${h}] connection ${O?"timed out":"failed"} - ${D}`);Te(this).debug(`[${h}] connection ${O?"timed out":"failed"} (${D})`,Nt({retryOfRequestLogID:i,url:f,durationMs:v-_,message:T.message}));return this.retryRequest(u,n,i!==null&&i!==void 0?i:h)}Te(this).info(`[${h}] connection ${O?"timed out":"failed"} - error; no more retries left`);Te(this).debug(`[${h}] connection ${O?"timed out":"failed"} (error; no more retries left)`,Nt({retryOfRequestLogID:i,url:f,durationMs:v-_,message:T.message}));if(O){throw new ji}throw new jt({cause:T})}const G=`[${h}${m}] ${d.method} ${f} ${T.ok?"succeeded":"failed"} with status ${T.status} in ${v-_}ms`;if(!T.ok){const D=await this.shouldRetry(T);if(n&&D){const k=`retrying, ${n} attempts remaining`;await Pv(T.body);Te(this).info(`${G} - ${k}`);Te(this).debug(`[${h}] response error (${k})`,Nt({retryOfRequestLogID:i,url:T.url,status:T.status,headers:T.headers,durationMs:v-_}));return this.retryRequest(u,n,i!==null&&i!==void 0?i:h,T.headers)}const O=D?`error; no more retries left`:`error; not retryable`;Te(this).info(`${G} - ${O}`);const L=await T.text().catch(k=>_a(k).message);const R=Sv(L);const q=R?void 0:L;Te(this).debug(`[${h}] response error (${O})`,Nt({retryOfRequestLogID:i,url:T.url,status:T.status,headers:T.headers,message:q,durationMs:Date.now()-_}));const V=this.makeStatusError(T.status,R,q,T.headers);throw V}Te(this).info(G);Te(this).debug(`[${h}] response start`,Nt({retryOfRequestLogID:i,url:T.url,status:T.status,headers:T.headers,durationMs:v-_}));return{response:T,options:u,controller:A,requestLogID:h,retryOfRequestLogID:i,startTime:_}}async fetchWithTimeout(e,n,i,r){const o=n||{},{signal:l,method:u}=o,c=mt(o,["signal","method"]);const d=this._makeAbort(r);if(l)l.addEventListener("abort",d,{once:true});const f=setTimeout(d,i);const p=globalThis.ReadableStream&&c.body instanceof globalThis.ReadableStream||typeof c.body==="object"&&c.body!==null&&Symbol.asyncIterator in c.body;const h=Object.assign(Object.assign(Object.assign({signal:r.signal},p?{duplex:"half"}:{}),{method:"GET"}),c);if(u){h.method=u.toUpperCase()}try{return await this.fetch.call(void 0,e,h)}finally{clearTimeout(f)}}async shouldRetry(e){const n=e.headers.get("x-should-retry");if(n==="true")return true;if(n==="false")return false;if(e.status===408)return true;if(e.status===409)return true;if(e.status===429)return true;if(e.status>=500)return true;return false}async retryRequest(e,n,i,r){var o;let l;const u=r===null||r===void 0?void 0:r.get("retry-after-ms");if(u){const d=parseFloat(u);if(!Number.isNaN(d)){l=d}}const c=r===null||r===void 0?void 0:r.get("retry-after");if(c&&!l){const d=parseFloat(c);if(!Number.isNaN(d)){l=d*1e3}else{l=Date.parse(c)-Date.now()}}if(l===void 0){const d=(o=e.maxRetries)!==null&&o!==void 0?o:this.maxRetries;l=this.calculateDefaultRetryTimeoutMillis(n,d)}await Iv(l);return this.makeRequest(e,n-1,i)}calculateDefaultRetryTimeoutMillis(e,n){const i=.5;const r=8;const o=n-e;const l=Math.min(i*Math.pow(2,o),r);const u=1-Math.random()*.25;return l*u*1e3}async buildRequest(e,{retryCount:n=0}={}){var i,r,o;const l=Object.assign({},e);const{method:u,path:c,query:d,defaultBaseURL:f}=l;const p=this.buildURL(c,d,f);if("timeout"in l)vv("timeout",l.timeout);l.timeout=(i=l.timeout)!==null&&i!==void 0?i:this.timeout;const{bodyHeaders:h,body:m}=this.buildBody({options:l});const _=await this.buildHeaders({options:e,method:u,bodyHeaders:h,retryCount:n});const A=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({method:u,headers:_},l.signal&&{signal:l.signal}),globalThis.ReadableStream&&m instanceof globalThis.ReadableStream&&{duplex:"half"}),m&&{body:m}),(r=this.fetchOptions)!==null&&r!==void 0?r:{}),(o=l.fetchOptions)!==null&&o!==void 0?o:{});return{req:A,url:p,timeout:l.timeout}}async buildHeaders({options:e,method:n,bodyHeaders:i,retryCount:r}){let o={};if(this.idempotencyHeader&&n!=="get"){if(!e.idempotencyKey)e.idempotencyKey=this.defaultIdempotencyKey();o[this.idempotencyHeader]=e.idempotencyKey}const l=await this.authHeaders(e);let u=Sn([o,{Accept:"application/json","User-Agent":this.getUserAgent()},this._options.defaultHeaders,i,e.headers,l]);this.validateHeaders(u);return u.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:n}}){if(!e){return{bodyHeaders:void 0,body:void 0}}const i=Sn([n]);if(ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e==="string"&&i.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream){return{bodyHeaders:void 0,body:e}}else if(typeof e==="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next==="function")){return{bodyHeaders:void 0,body:Rv(e)}}else if(typeof e==="object"&&i.values.get("content-type")==="application/x-www-form-urlencoded"){return{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(e)}}else{return this.encoder({body:e,headers:i})}}};pr.DEFAULT_TIMEOUT=6e4;var ue=class extends pr{constructor(){super(...arguments);this.interactions=new ur(this);this.webhooks=new dr(this)}};Kf=ue;ue.GeminiNextGenAPIClient=Kf;ue.GeminiNextGenAPIClientError=Ce;ue.APIError=ve;ue.APIConnectionError=jt;ue.APIConnectionTimeoutError=ji;ue.APIUserAbortError=Rn;ue.NotFoundError=ir;ue.ConflictError=rr;ue.RateLimitError=sr;ue.BadRequestError=er;ue.AuthenticationError=tr;ue.InternalServerError=ar;ue.PermissionDeniedError=nr;ue.UnprocessableEntityError=or;ue.toFile=Gv;ue.Interactions=ur;ue.Webhooks=dr;var cf="x-goog-api-key";var In="https://www.googleapis.com/auth/cloud-platform";var Ia=class{constructor(e){if(e.apiKey!==void 0){this.apiKey=e.apiKey;return}const n=Wv(e.googleAuthOptions);this.googleAuth=new pf.GoogleAuth(n)}async addAuthHeaders(e,n){if(this.apiKey!==void 0){if(this.apiKey.startsWith("auth_tokens/")){throw new Error("Ephemeral tokens are only supported by the live API.")}this.addKeyHeader(e);return}return this.addGoogleAuthHeaders(e,n)}addKeyHeader(e){if(e.get(cf)!==null){return}if(this.apiKey===void 0){throw new Error("Trying to set API key header but apiKey is not set")}e.append(cf,this.apiKey)}async addGoogleAuthHeaders(e,n){if(this.googleAuth===void 0){throw new Error("Trying to set google-auth headers but googleAuth is unset")}const i=await this.googleAuth.getRequestHeaders(n);for(const[r,o]of i){if(e.get(r)!==null){continue}e.append(r,o)}}};function Wv(t){let e;if(!t){e={scopes:[In]};return e}else{e=t;if(!e.scopes){e.scopes=[In];return e}else if(typeof e.scopes==="string"&&e.scopes!==In||Array.isArray(e.scopes)&&e.scopes.indexOf(In)<0){throw new Error(`Invalid auth scopes. Scopes must include: ${In}`)}return e}}var wa=class{async download(e,n){if(e.downloadPath){const i=await Yv(e,n);if(i instanceof _t){const r=Py(e.downloadPath);const o=My.fromWeb(i.responseInternal.body);o.pipe(r);await ky(r)}else{try{await Ny(e.downloadPath,i,{encoding:"base64"})}catch(r){throw new Error(`Failed to write file to ${e.downloadPath}: ${r}`)}}}}};async function Yv(t,e){var n,i,r;const o=Fa(t.file);if(o!==void 0){return await e.request({path:`files/${o}:download`,httpMethod:"GET",queryParams:{"alt":"media"},httpOptions:(n=t.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=t.config)===null||i===void 0?void 0:i.abortSignal})}else if(Af(t.file)){const l=(r=t.file.video)===null||r===void 0?void 0:r.videoBytes;if(typeof l==="string"){return l}else{throw new Error("Failed to download generated video, Uri or videoBytes not found.")}}else if(Cf(t.file)){const l=t.file.videoBytes;if(typeof l==="string"){return l}else{throw new Error("Failed to download video, Uri or videoBytes not found.")}}else{throw new Error("Unsupported file type")}}var Ra=class{create(e,n,i){return new Pa(e,n,i)}};var Pa=class{constructor(e,n,i){this.url=e;this.headers=n;this.callbacks=i}connect(){this.ws=new Ka.default(this.url,{headers:this.headers});this.ws.onopen=this.callbacks.onopen;this.ws.onerror=this.callbacks.onerror;this.ws.onclose=this.callbacks.onclose;this.ws.onmessage=this.callbacks.onmessage}send(e){if(this.ws===void 0){throw new Error("WebSocket is not connected")}this.ws.send(e)}close(){if(this.ws===void 0){throw new Error("WebSocket is not connected")}this.ws.close()}};function zv(t,e){const n={};const i=s(t,["name"]);if(i!=null){a(n,["_url","name"],i)}return n}function Xv(t,e){const n={};const i=s(t,["name"]);if(i!=null){a(n,["_url","name"],i)}return n}function Qv(t,e){const n={};const i=s(t,["sdkHttpResponse"]);if(i!=null){a(n,["sdkHttpResponse"],i)}return n}function Zv(t,e){const n={};const i=s(t,["sdkHttpResponse"]);if(i!=null){a(n,["sdkHttpResponse"],i)}return n}function jv(t,e,n){const i={};if(s(t,["validationDataset"])!==void 0){throw new Error("validationDataset parameter is not supported in Gemini API.")}const r=s(t,["tunedModelDisplayName"]);if(e!==void 0&&r!=null){a(e,["displayName"],r)}if(s(t,["description"])!==void 0){throw new Error("description parameter is not supported in Gemini API.")}const o=s(t,["epochCount"]);if(e!==void 0&&o!=null){a(e,["tuningTask","hyperparameters","epochCount"],o)}const l=s(t,["learningRateMultiplier"]);if(l!=null){a(i,["tuningTask","hyperparameters","learningRateMultiplier"],l)}if(s(t,["exportLastCheckpointOnly"])!==void 0){throw new Error("exportLastCheckpointOnly parameter is not supported in Gemini API.")}if(s(t,["preTunedModelCheckpointId"])!==void 0){throw new Error("preTunedModelCheckpointId parameter is not supported in Gemini API.")}if(s(t,["adapterSize"])!==void 0){throw new Error("adapterSize parameter is not supported in Gemini API.")}if(s(t,["tuningMode"])!==void 0){throw new Error("tuningMode parameter is not supported in Gemini API.")}if(s(t,["customBaseModel"])!==void 0){throw new Error("customBaseModel parameter is not supported in Gemini API.")}const u=s(t,["batchSize"]);if(e!==void 0&&u!=null){a(e,["tuningTask","hyperparameters","batchSize"],u)}const c=s(t,["learningRate"]);if(e!==void 0&&c!=null){a(e,["tuningTask","hyperparameters","learningRate"],c)}if(s(t,["labels"])!==void 0){throw new Error("labels parameter is not supported in Gemini API.")}if(s(t,["beta"])!==void 0){throw new Error("beta parameter is not supported in Gemini API.")}if(s(t,["baseTeacherModel"])!==void 0){throw new Error("baseTeacherModel parameter is not supported in Gemini API.")}if(s(t,["tunedTeacherModelSource"])!==void 0){throw new Error("tunedTeacherModelSource parameter is not supported in Gemini API.")}if(s(t,["sftLossWeightMultiplier"])!==void 0){throw new Error("sftLossWeightMultiplier parameter is not supported in Gemini API.")}if(s(t,["outputUri"])!==void 0){throw new Error("outputUri parameter is not supported in Gemini API.")}if(s(t,["encryptionSpec"])!==void 0){throw new Error("encryptionSpec parameter is not supported in Gemini API.")}return i}function eS(t,e,n){const i={};let r=s(n,["config","method"]);if(r===void 0){r="SUPERVISED_FINE_TUNING"}if(r==="SUPERVISED_FINE_TUNING"){const R=s(t,["validationDataset"]);if(e!==void 0&&R!=null){a(e,["supervisedTuningSpec"],ks(R))}}else if(r==="PREFERENCE_TUNING"){const R=s(t,["validationDataset"]);if(e!==void 0&&R!=null){a(e,["preferenceOptimizationSpec"],ks(R))}}else if(r==="DISTILLATION"){const R=s(t,["validationDataset"]);if(e!==void 0&&R!=null){a(e,["distillationSpec"],ks(R))}}const o=s(t,["tunedModelDisplayName"]);if(e!==void 0&&o!=null){a(e,["tunedModelDisplayName"],o)}const l=s(t,["description"]);if(e!==void 0&&l!=null){a(e,["description"],l)}let u=s(n,["config","method"]);if(u===void 0){u="SUPERVISED_FINE_TUNING"}if(u==="SUPERVISED_FINE_TUNING"){const R=s(t,["epochCount"]);if(e!==void 0&&R!=null){a(e,["supervisedTuningSpec","hyperParameters","epochCount"],R)}}else if(u==="PREFERENCE_TUNING"){const R=s(t,["epochCount"]);if(e!==void 0&&R!=null){a(e,["preferenceOptimizationSpec","hyperParameters","epochCount"],R)}}else if(u==="DISTILLATION"){const R=s(t,["epochCount"]);if(e!==void 0&&R!=null){a(e,["distillationSpec","hyperParameters","epochCount"],R)}}let c=s(n,["config","method"]);if(c===void 0){c="SUPERVISED_FINE_TUNING"}if(c==="SUPERVISED_FINE_TUNING"){const R=s(t,["learningRateMultiplier"]);if(e!==void 0&&R!=null){a(e,["supervisedTuningSpec","hyperParameters","learningRateMultiplier"],R)}}else if(c==="PREFERENCE_TUNING"){const R=s(t,["learningRateMultiplier"]);if(e!==void 0&&R!=null){a(e,["preferenceOptimizationSpec","hyperParameters","learningRateMultiplier"],R)}}else if(c==="DISTILLATION"){const R=s(t,["learningRateMultiplier"]);if(e!==void 0&&R!=null){a(e,["distillationSpec","hyperParameters","learningRateMultiplier"],R)}}let d=s(n,["config","method"]);if(d===void 0){d="SUPERVISED_FINE_TUNING"}if(d==="SUPERVISED_FINE_TUNING"){const R=s(t,["exportLastCheckpointOnly"]);if(e!==void 0&&R!=null){a(e,["supervisedTuningSpec","exportLastCheckpointOnly"],R)}}else if(d==="PREFERENCE_TUNING"){const R=s(t,["exportLastCheckpointOnly"]);if(e!==void 0&&R!=null){a(e,["preferenceOptimizationSpec","exportLastCheckpointOnly"],R)}}else if(d==="DISTILLATION"){const R=s(t,["exportLastCheckpointOnly"]);if(e!==void 0&&R!=null){a(e,["distillationSpec","exportLastCheckpointOnly"],R)}}let f=s(n,["config","method"]);if(f===void 0){f="SUPERVISED_FINE_TUNING"}if(f==="SUPERVISED_FINE_TUNING"){const R=s(t,["adapterSize"]);if(e!==void 0&&R!=null){a(e,["supervisedTuningSpec","hyperParameters","adapterSize"],R)}}else if(f==="PREFERENCE_TUNING"){const R=s(t,["adapterSize"]);if(e!==void 0&&R!=null){a(e,["preferenceOptimizationSpec","hyperParameters","adapterSize"],R)}}else if(f==="DISTILLATION"){const R=s(t,["adapterSize"]);if(e!==void 0&&R!=null){a(e,["distillationSpec","hyperParameters","adapterSize"],R)}}let p=s(n,["config","method"]);if(p===void 0){p="SUPERVISED_FINE_TUNING"}if(p==="SUPERVISED_FINE_TUNING"){const R=s(t,["tuningMode"]);if(e!==void 0&&R!=null){a(e,["supervisedTuningSpec","tuningMode"],R)}}else if(p==="DISTILLATION"){const R=s(t,["tuningMode"]);if(e!==void 0&&R!=null){a(e,["distillationSpec","tuningMode"],R)}}const h=s(t,["customBaseModel"]);if(e!==void 0&&h!=null){a(e,["customBaseModel"],h)}let m=s(n,["config","method"]);if(m===void 0){m="SUPERVISED_FINE_TUNING"}if(m==="SUPERVISED_FINE_TUNING"){const R=s(t,["batchSize"]);if(e!==void 0&&R!=null){a(e,["supervisedTuningSpec","hyperParameters","batchSize"],R)}}else if(m==="DISTILLATION"){const R=s(t,["batchSize"]);if(e!==void 0&&R!=null){a(e,["distillationSpec","hyperParameters","batchSize"],R)}}let _=s(n,["config","method"]);if(_===void 0){_="SUPERVISED_FINE_TUNING"}if(_==="SUPERVISED_FINE_TUNING"){const R=s(t,["learningRate"]);if(e!==void 0&&R!=null){a(e,["supervisedTuningSpec","hyperParameters","learningRate"],R)}}else if(_==="DISTILLATION"){const R=s(t,["learningRate"]);if(e!==void 0&&R!=null){a(e,["distillationSpec","hyperParameters","learningRate"],R)}}const A=s(t,["labels"]);if(e!==void 0&&A!=null){a(e,["labels"],A)}const T=s(t,["beta"]);if(e!==void 0&&T!=null){a(e,["preferenceOptimizationSpec","hyperParameters","beta"],T)}const v=s(t,["baseTeacherModel"]);if(e!==void 0&&v!=null){a(e,["distillationSpec","baseTeacherModel"],v)}const G=s(t,["tunedTeacherModelSource"]);if(e!==void 0&&G!=null){a(e,["distillationSpec","tunedTeacherModelSource"],G)}const D=s(t,["sftLossWeightMultiplier"]);if(e!==void 0&&D!=null){a(e,["distillationSpec","hyperParameters","sftLossWeightMultiplier"],D)}const O=s(t,["outputUri"]);if(e!==void 0&&O!=null){a(e,["outputUri"],O)}const L=s(t,["encryptionSpec"]);if(e!==void 0&&L!=null){a(e,["encryptionSpec"],L)}return i}function tS(t,e){const n={};const i=s(t,["baseModel"]);if(i!=null){a(n,["baseModel"],i)}const r=s(t,["preTunedModel"]);if(r!=null){a(n,["preTunedModel"],r)}const o=s(t,["trainingDataset"]);if(o!=null){uS(o)}const l=s(t,["config"]);if(l!=null){jv(l,n)}return n}function nS(t,e){const n={};const i=s(t,["baseModel"]);if(i!=null){a(n,["baseModel"],i)}const r=s(t,["preTunedModel"]);if(r!=null){a(n,["preTunedModel"],r)}const o=s(t,["trainingDataset"]);if(o!=null){cS(o,n,e)}const l=s(t,["config"]);if(l!=null){eS(l,n,e)}return n}function iS(t,e){const n={};const i=s(t,["name"]);if(i!=null){a(n,["_url","name"],i)}return n}function rS(t,e){const n={};const i=s(t,["name"]);if(i!=null){a(n,["_url","name"],i)}return n}function oS(t,e,n){const i={};const r=s(t,["pageSize"]);if(e!==void 0&&r!=null){a(e,["_query","pageSize"],r)}const o=s(t,["pageToken"]);if(e!==void 0&&o!=null){a(e,["_query","pageToken"],o)}const l=s(t,["filter"]);if(e!==void 0&&l!=null){a(e,["_query","filter"],l)}return i}function sS(t,e){const n={};const i=s(t,["config"]);if(i!=null){oS(i,n)}return n}function aS(t,e){const n={};const i=s(t,["sdkHttpResponse"]);if(i!=null){a(n,["sdkHttpResponse"],i)}const r=s(t,["nextPageToken"]);if(r!=null){a(n,["nextPageToken"],r)}const o=s(t,["tuningJobs"]);if(o!=null){let l=o;if(Array.isArray(l)){l=l.map(u=>{return Na(u)})}a(n,["tuningJobs"],l)}return n}function lS(t,e){const n={};const i=s(t,["name"]);if(i!=null){a(n,["model"],i)}const r=s(t,["name"]);if(r!=null){a(n,["endpoint"],r)}return n}function uS(t,e){const n={};if(s(t,["gcsUri"])!==void 0){throw new Error("gcsUri parameter is not supported in Gemini API.")}if(s(t,["vertexDatasetResource"])!==void 0){throw new Error("vertexDatasetResource parameter is not supported in Gemini API.")}const i=s(t,["examples"]);if(i!=null){let r=i;if(Array.isArray(r)){r=r.map(o=>{return o})}a(n,["examples","examples"],r)}return n}function cS(t,e,n){const i={};let r=s(n,["config","method"]);if(r===void 0){r="SUPERVISED_FINE_TUNING"}if(r==="SUPERVISED_FINE_TUNING"){const l=s(t,["gcsUri"]);if(e!==void 0&&l!=null){a(e,["supervisedTuningSpec","trainingDatasetUri"],l)}}else if(r==="PREFERENCE_TUNING"){const l=s(t,["gcsUri"]);if(e!==void 0&&l!=null){a(e,["preferenceOptimizationSpec","trainingDatasetUri"],l)}}else if(r==="DISTILLATION"){const l=s(t,["gcsUri"]);if(e!==void 0&&l!=null){a(e,["distillationSpec","promptDatasetUri"],l)}}let o=s(n,["config","method"]);if(o===void 0){o="SUPERVISED_FINE_TUNING"}if(o==="SUPERVISED_FINE_TUNING"){const l=s(t,["vertexDatasetResource"]);if(e!==void 0&&l!=null){a(e,["supervisedTuningSpec","trainingDatasetUri"],l)}}else if(o==="PREFERENCE_TUNING"){const l=s(t,["vertexDatasetResource"]);if(e!==void 0&&l!=null){a(e,["preferenceOptimizationSpec","trainingDatasetUri"],l)}}else if(o==="DISTILLATION"){const l=s(t,["vertexDatasetResource"]);if(e!==void 0&&l!=null){a(e,["distillationSpec","promptDatasetUri"],l)}}if(s(t,["examples"])!==void 0){throw new Error("examples parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).")}return i}function dS(t,e){const n={};const i=s(t,["sdkHttpResponse"]);if(i!=null){a(n,["sdkHttpResponse"],i)}const r=s(t,["name"]);if(r!=null){a(n,["name"],r)}const o=s(t,["state"]);if(o!=null){a(n,["state"],Tf(o))}const l=s(t,["createTime"]);if(l!=null){a(n,["createTime"],l)}const u=s(t,["tuningTask","startTime"]);if(u!=null){a(n,["startTime"],u)}const c=s(t,["tuningTask","completeTime"]);if(c!=null){a(n,["endTime"],c)}const d=s(t,["updateTime"]);if(d!=null){a(n,["updateTime"],d)}const f=s(t,["description"]);if(f!=null){a(n,["description"],f)}const p=s(t,["baseModel"]);if(p!=null){a(n,["baseModel"],p)}const h=s(t,["_self"]);if(h!=null){a(n,["tunedModel"],lS(h))}return n}function Na(t,e){const n={};const i=s(t,["sdkHttpResponse"]);if(i!=null){a(n,["sdkHttpResponse"],i)}const r=s(t,["name"]);if(r!=null){a(n,["name"],r)}const o=s(t,["state"]);if(o!=null){a(n,["state"],Tf(o))}const l=s(t,["createTime"]);if(l!=null){a(n,["createTime"],l)}const u=s(t,["startTime"]);if(u!=null){a(n,["startTime"],u)}const c=s(t,["endTime"]);if(c!=null){a(n,["endTime"],c)}const d=s(t,["updateTime"]);if(d!=null){a(n,["updateTime"],d)}const f=s(t,["error"]);if(f!=null){a(n,["error"],f)}const p=s(t,["description"]);if(p!=null){a(n,["description"],p)}const h=s(t,["baseModel"]);if(h!=null){a(n,["baseModel"],h)}const m=s(t,["tunedModel"]);if(m!=null){a(n,["tunedModel"],m)}const _=s(t,["preTunedModel"]);if(_!=null){a(n,["preTunedModel"],_)}const A=s(t,["supervisedTuningSpec"]);if(A!=null){a(n,["supervisedTuningSpec"],A)}const T=s(t,["preferenceOptimizationSpec"]);if(T!=null){a(n,["preferenceOptimizationSpec"],T)}const v=s(t,["distillationSpec"]);if(v!=null){a(n,["distillationSpec"],v)}const G=s(t,["tuningDataStats"]);if(G!=null){a(n,["tuningDataStats"],G)}const D=s(t,["encryptionSpec"]);if(D!=null){a(n,["encryptionSpec"],D)}const O=s(t,["partnerModelTuningSpec"]);if(O!=null){a(n,["partnerModelTuningSpec"],O)}const L=s(t,["customBaseModel"]);if(L!=null){a(n,["customBaseModel"],L)}const R=s(t,["evaluateDatasetRuns"]);if(R!=null){let Ie=R;if(Array.isArray(Ie)){Ie=Ie.map(ce=>{return ce})}a(n,["evaluateDatasetRuns"],Ie)}const q=s(t,["experiment"]);if(q!=null){a(n,["experiment"],q)}const V=s(t,["fullFineTuningSpec"]);if(V!=null){a(n,["fullFineTuningSpec"],V)}const k=s(t,["labels"]);if(k!=null){a(n,["labels"],k)}const $=s(t,["outputUri"]);if($!=null){a(n,["outputUri"],$)}const Y=s(t,["pipelineJob"]);if(Y!=null){a(n,["pipelineJob"],Y)}const Q=s(t,["serviceAccount"]);if(Q!=null){a(n,["serviceAccount"],Q)}const oe=s(t,["tunedModelDisplayName"]);if(oe!=null){a(n,["tunedModelDisplayName"],oe)}const ee=s(t,["tuningJobState"]);if(ee!=null){a(n,["tuningJobState"],ee)}const re=s(t,["veoTuningSpec"]);if(re!=null){a(n,["veoTuningSpec"],re)}const le=s(t,["distillationSamplingSpec"]);if(le!=null){a(n,["distillationSamplingSpec"],le)}const Se=s(t,["tuningJobMetadata"]);if(Se!=null){a(n,["tuningJobMetadata"],Se)}return n}function fS(t,e){const n={};const i=s(t,["sdkHttpResponse"]);if(i!=null){a(n,["sdkHttpResponse"],i)}const r=s(t,["name"]);if(r!=null){a(n,["name"],r)}const o=s(t,["metadata"]);if(o!=null){a(n,["metadata"],o)}const l=s(t,["done"]);if(l!=null){a(n,["done"],l)}const u=s(t,["error"]);if(u!=null){a(n,["error"],u)}return n}function ks(t,e){const n={};const i=s(t,["gcsUri"]);if(i!=null){a(n,["validationDatasetUri"],i)}const r=s(t,["vertexDatasetResource"]);if(r!=null){a(n,["validationDatasetUri"],r)}return n}var Ma=class extends We{constructor(e){super();this.apiClient=e;this.list=async(n={})=>{return new at(st.PAGED_ITEM_TUNING_JOBS,i=>this.listInternal(i),await this.listInternal(n),n)};this.get=async n=>{return await this.getInternal(n)};this.tune=async n=>{var i;if(this.apiClient.isVertexAI()){if(n.baseModel.startsWith("projects/")){const r={tunedModelName:n.baseModel};if((i=n.config)===null||i===void 0?void 0:i.preTunedModelCheckpointId){r.checkpointId=n.config.preTunedModelCheckpointId}const o=Object.assign(Object.assign({},n),{preTunedModel:r});o.baseModel=void 0;return await this.tuneInternal(o)}else{const r=Object.assign({},n);return await this.tuneInternal(r)}}else{const r=Object.assign({},n);const o=await this.tuneMldevInternal(r);let l="";if(o["metadata"]!==void 0&&o["metadata"]["tunedModel"]!==void 0){l=o["metadata"]["tunedModel"]}else if(o["name"]!==void 0&&o["name"].includes("/operations/")){l=o["name"].split("/operations/")[0]}const u={name:l,state:Ds.JOB_STATE_QUEUED};return u}}}async getInternal(e){var n,i,r,o;let l;let u="";let c={};if(this.apiClient.isVertexAI()){const d=rS(e);u=H("{name}",d["_url"]);c=d["_query"];delete d["_url"];delete d["_query"];l=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>{return f.json().then(p=>{const h=p;h.sdkHttpResponse={headers:f.headers};return h})});return l.then(f=>{const p=Na(f);return p})}else{const d=iS(e);u=H("{name}",d["_url"]);c=d["_query"];delete d["_url"];delete d["_query"];l=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(r=e.config)===null||r===void 0?void 0:r.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>{return f.json().then(p=>{const h=p;h.sdkHttpResponse={headers:f.headers};return h})});return l.then(f=>{const p=dS(f);return p})}}async listInternal(e){var n,i;let r;let o="";let l={};if(this.apiClient.isVertexAI()){const u=sS(e);o=H("tuningJobs",u["_url"]);l=u["_query"];delete u["_url"];delete u["_query"];r=this.apiClient.request({path:o,queryParams:l,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(c=>{return c.json().then(d=>{const f=d;f.sdkHttpResponse={headers:c.headers};return f})});return r.then(c=>{const d=aS(c);const f=new qs;Object.assign(f,d);return f})}else{throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}}async cancel(e){var n,i,r,o;let l;let u="";let c={};if(this.apiClient.isVertexAI()){const d=Xv(e);u=H("{name}:cancel",d["_url"]);c=d["_query"];delete d["_url"];delete d["_query"];l=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>{return f.json().then(p=>{const h=p;h.sdkHttpResponse={headers:f.headers};return h})});return l.then(f=>{const p=Zv(f);const h=new Ki;Object.assign(h,p);return h})}else{const d=zv(e);u=H("{name}:cancel",d["_url"]);c=d["_query"];delete d["_url"];delete d["_query"];l=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(r=e.config)===null||r===void 0?void 0:r.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>{return f.json().then(p=>{const h=p;h.sdkHttpResponse={headers:f.headers};return h})});return l.then(f=>{const p=Qv(f);const h=new Ki;Object.assign(h,p);return h})}}async tuneInternal(e){var n,i;let r;let o="";let l={};if(this.apiClient.isVertexAI()){const u=nS(e,e);o=H("tuningJobs",u["_url"]);l=u["_query"];delete u["_url"];delete u["_query"];r=this.apiClient.request({path:o,queryParams:l,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(c=>{return c.json().then(d=>{const f=d;f.sdkHttpResponse={headers:c.headers};return f})});return r.then(c=>{const d=Na(c);return d})}else{throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}}async tuneMldevInternal(e){var n,i;let r;let o="";let l={};if(this.apiClient.isVertexAI()){throw new Error("This method is only supported by the Gemini Developer API.")}else{const u=tS(e);o=H("tunedModels",u["_url"]);l=u["_query"];delete u["_url"];delete u["_query"];r=this.apiClient.request({path:o,queryParams:l,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(c=>{return c.json().then(d=>{const f=d;f.sdkHttpResponse={headers:c.headers};return f})});return r.then(c=>{const d=fS(c);return d})}}};var Wf=1024*1024*8;var Yf=3;var zf=1e3;var Xf=2;var yt="x-goog-upload-status";async function pS(t,e,n,i){var r;const o=await Qf(t,e,n,i);const l=await(o===null||o===void 0?void 0:o.json());if(((r=o===null||o===void 0?void 0:o.headers)===null||r===void 0?void 0:r[yt])!=="final"){throw new Error("Failed to upload file: Upload status is not finalized.")}return l["file"]}async function hS(t,e,n,i){var r;const o=await Qf(t,e,n,i);const l=await(o===null||o===void 0?void 0:o.json());if(((r=o===null||o===void 0?void 0:o.headers)===null||r===void 0?void 0:r[yt])!=="final"){throw new Error("Failed to upload file: Upload status is not finalized.")}const u=Ua(l);const c=new Xi;Object.assign(c,u);return c}async function Qf(t,e,n,i){var r,o,l;let u=e;const c=(i===null||i===void 0?void 0:i.baseUrl)||((r=n.clientOptions.httpOptions)===null||r===void 0?void 0:r.baseUrl);if(c){const m=new URL(c);const _=new URL(e);_.protocol=m.protocol;_.host=m.host;_.port=m.port;u=_.toString()}let d=0;let f=0;let p=new _t(new Response);let h="upload";d=t.size;while(f<d){const m=Math.min(Wf,d-f);const _=t.slice(f,f+m);if(f+m>=d){h+=", finalize"}let A=0;let T=zf;while(A<Yf){const v=Object.assign(Object.assign({},(i===null||i===void 0?void 0:i.headers)||{}),{"X-Goog-Upload-Command":h,"X-Goog-Upload-Offset":String(f),"Content-Length":String(m)});p=await n.request({path:"",body:_,httpMethod:"POST",httpOptions:Object.assign(Object.assign({},i),{apiVersion:"",baseUrl:u,headers:v})});if((o=p===null||p===void 0?void 0:p.headers)===null||o===void 0?void 0:o[yt]){break}A++;await Zf(T);T=T*Xf}f+=m;if(((l=p===null||p===void 0?void 0:p.headers)===null||l===void 0?void 0:l[yt])!=="active"){break}if(d<=f){throw new Error("All content has been uploaded, but the upload status is not finalized.")}}return p}async function gS(t){const e={size:t.size,type:t.type};return e}function Zf(t){return new Promise(e=>setTimeout(e,t))}var ka=class{async stat(e){const n={size:0,type:void 0};if(typeof e==="string"){const i=await gr.stat(e);n.size=i.size;n.type=this.inferMimeType(e);return n}else{return await gS(e)}}async upload(e,n,i,r){if(typeof e==="string"){return await this.uploadFileFromPath(e,n,i,r)}else{return pS(e,n,i,r)}}async uploadToFileSearchStore(e,n,i,r){if(typeof e==="string"){return await this.uploadFileToFileSearchStoreFromPath(e,n,i,r)}else{return hS(e,n,i,r)}}inferMimeType(e){const n=e.slice(e.lastIndexOf(".")+1);const i={"aac":"audio/aac","abw":"application/x-abiword","arc":"application/x-freearc","avi":"video/x-msvideo","azw":"application/vnd.amazon.ebook","bin":"application/octet-stream","bmp":"image/bmp","bz":"application/x-bzip","bz2":"application/x-bzip2","csh":"application/x-csh","css":"text/css","csv":"text/csv","doc":"application/msword","docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document","eot":"application/vnd.ms-fontobject","epub":"application/epub+zip","gz":"application/gzip","gif":"image/gif","htm":"text/html","html":"text/html","ico":"image/vnd.microsoft.icon","ics":"text/calendar","jar":"application/java-archive","jpeg":"image/jpeg","jpg":"image/jpeg","js":"text/javascript","json":"application/json","jsonld":"application/ld+json","kml":"application/vnd.google-earth.kml+xml","kmz":"application/vnd.google-earth.kmz+xml","mjs":"text/javascript","mp3":"audio/mpeg","mp4":"video/mp4","mpeg":"video/mpeg","mpkg":"application/vnd.apple.installer+xml","odt":"application/vnd.oasis.opendocument.text","oga":"audio/ogg","ogv":"video/ogg","ogx":"application/ogg","opus":"audio/opus","otf":"font/otf","png":"image/png","pdf":"application/pdf","php":"application/x-httpd-php","ppt":"application/vnd.ms-powerpoint","pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation","rar":"application/vnd.rar","rtf":"application/rtf","sh":"application/x-sh","svg":"image/svg+xml","swf":"application/x-shockwave-flash","tar":"application/x-tar","tif":"image/tiff","tiff":"image/tiff","ts":"video/mp2t","ttf":"font/ttf","txt":"text/plain","vsd":"application/vnd.visio","wav":"audio/wav","weba":"audio/webm","webm":"video/webm","webp":"image/webp","woff":"font/woff","woff2":"font/woff2","xhtml":"application/xhtml+xml","xls":"application/vnd.ms-excel","xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","xml":"application/xml","xul":"application/vnd.mozilla.xul+xml","zip":"application/zip","3gp":"video/3gpp","3g2":"video/3gpp2","7z":"application/x-7z-compressed"};const r=i[n.toLowerCase()];return r}async uploadFileFromPath(e,n,i,r){var o;const l=await this.uploadFileFromPathInternal(e,n,i,r);const u=await(l===null||l===void 0?void 0:l.json());if(((o=l===null||l===void 0?void 0:l.headers)===null||o===void 0?void 0:o[yt])!=="final"){throw new Error("Failed to upload file: Upload status is not finalized.")}return u["file"]}async uploadFileToFileSearchStoreFromPath(e,n,i,r){var o;const l=await this.uploadFileFromPathInternal(e,n,i,r);const u=await(l===null||l===void 0?void 0:l.json());if(((o=l===null||l===void 0?void 0:l.headers)===null||o===void 0?void 0:o[yt])!=="final"){throw new Error("Failed to upload file: Upload status is not finalized.")}const c=Ua(u);const d=new Xi;Object.assign(d,c);return d}async uploadFileFromPathInternal(e,n,i,r){var o,l,u;let c=n;const d=(r===null||r===void 0?void 0:r.baseUrl)||((o=i.clientOptions.httpOptions)===null||o===void 0?void 0:o.baseUrl);if(d){const T=new URL(d);const v=new URL(n);v.protocol=T.protocol;v.host=T.host;v.port=T.port;c=v.toString()}let f=0;let p=0;let h=new _t(new Response);let m="upload";let _;const A=hf.basename(e);try{_=await gr.open(e,"r");if(!_){throw new Error(`Failed to open file`)}f=(await _.stat()).size;while(p<f){const T=Math.min(Wf,f-p);if(p+T>=f){m+=", finalize"}const v=new Uint8Array(T);const{bytesRead:G}=await _.read(v,0,T,p);if(G!==T){throw new Error(`Failed to read ${T} bytes from file at offset ${p}. bytes actually read: ${G}`)}const D=new Blob([v]);let O=0;let L=zf;while(O<Yf){const R=Object.assign(Object.assign({},(r===null||r===void 0?void 0:r.headers)||{}),{"X-Goog-Upload-Command":m,"X-Goog-Upload-Offset":String(p),"Content-Length":String(G),"X-Goog-Upload-File-Name":A});h=await i.request({path:"",body:D,httpMethod:"POST",httpOptions:Object.assign(Object.assign({},r),{apiVersion:"",baseUrl:c,headers:R})});if((l=h===null||h===void 0?void 0:h.headers)===null||l===void 0?void 0:l[yt]){break}O++;await Zf(L);L=L*Xf}p+=G;if(((u=h===null||h===void 0?void 0:h.headers)===null||u===void 0?void 0:u[yt])!=="active"){break}if(f<=p){throw new Error("All content has been uploaded, but the upload status is not finalized.")}}return h}finally{if(_){await _.close()}}}};var xa=class extends ia{async registerFiles(e){if(typeof process==="undefined"||!process.versions||!process.versions.node){throw new Error("registerFiles is only supported in Node.js environments.")}const n=e.auth;const i=await n.getRequestHeaders();const r=e.config||{};const o=r.httpOptions||{};const l=Object.assign({},o.headers||{});if(i){if(typeof i[Symbol.iterator]==="function"){for(const[u,c]of i){l[u]=c}}else{for(const[u,c]of Object.entries(i)){l[u]=c}}}return this._registerFiles({uris:e.uris,config:Object.assign(Object.assign({},r),{httpOptions:Object.assign(Object.assign({},o),{headers:l})})})}};var mS="gl-node/";function yS(t){var e;if(t.enterprise!==void 0||t.vertexai!==void 0){if(t.enterprise!==void 0&&t.vertexai!==void 0&&t.enterprise!==t.vertexai){throw new Error("enterprise and vertexAI flags have conflicting values, please set enterprise value only.")}return(e=t.enterprise)!==null&&e!==void 0?e:t.vertexai}const n=Et("GOOGLE_GENAI_USE_ENTERPRISE");const i=Et("GOOGLE_GENAI_USE_VERTEXAI");const r=ff(n);const o=ff(i);if(n!==void 0&&i!==void 0&&r!==o){console.warn("Warning: Both GOOGLE_GENAI_USE_ENTERPRISE and GOOGLE_GENAI_USE_VERTEXAI are set with conflicting values. The value of GOOGLE_GENAI_USE_ENTERPRISE will be used.")}if(n!==void 0){return r}if(i!==void 0){return o}return false}var df=class{getNextGenClient(){var e;const n=this.httpOptions;if(this._nextGenClient===void 0){this._nextGenClient=new ue({baseURL:this.apiClient.getBaseUrl(),apiKey:this.apiKey,apiVersion:this.apiClient.getApiVersion(),clientAdapter:this.apiClient,defaultHeaders:this.apiClient.getDefaultHeaders(),timeout:n===null||n===void 0?void 0:n.timeout,maxRetries:(e=n===null||n===void 0?void 0:n.retryOptions)===null||e===void 0?void 0:e.attempts})}if(n===null||n===void 0?void 0:n.extraBody){console.warn("GoogleGenAI.interactions: Client level httpOptions.extraBody is not supported by the interactions client and will be ignored.")}return this._nextGenClient}get interactions(){if(this._interactions!==void 0){return this._interactions}console.warn("GoogleGenAI.interactions: Interactions usage is experimental and may change in future versions.");this._interactions=this.getNextGenClient().interactions;return this._interactions}get webhooks(){if(this._webhooks!==void 0){return this._webhooks}this._webhooks=this.getNextGenClient().webhooks;return this._webhooks}constructor(e){var n,i,r,o;if((e.project||e.location)&&e.apiKey){throw new Error("Project/location and API key are mutually exclusive in the client initializer.")}this.vertexai=yS(e);const l=ES();const u=Et("GOOGLE_CLOUD_PROJECT");const c=Et("GOOGLE_CLOUD_LOCATION");this.apiKey=(n=e.apiKey)!==null&&n!==void 0?n:l;this.project=(i=e.project)!==null&&i!==void 0?i:u;this.location=(r=e.location)!==null&&r!==void 0?r:c;if(!this.vertexai&&!this.apiKey){console.warn("API key should be set when using the Gemini API.")}if(this.vertexai){if((o=e.googleAuthOptions)===null||o===void 0?void 0:o.credentials){console.debug("The user provided Google Cloud credentials will take precedence over the API key from the environment variable.");this.apiKey=void 0}if((u||c)&&e.apiKey){console.debug("The user provided Vertex AI API key will take precedence over the project/location from the environment variables.");this.project=void 0;this.location=void 0}else if((e.project||e.location)&&l){console.debug("The user provided project/location will take precedence over the API key from the environment variables.");this.apiKey=void 0}else if((u||c)&&l){console.debug("The project/location from the environment variables will take precedence over the API key from the environment variables.");this.apiKey=void 0}if(!this.location&&!this.apiKey){this.location="global"}}const d=Ly(e.httpOptions,this.vertexai,Et("GOOGLE_VERTEX_BASE_URL"),Et("GOOGLE_GEMINI_BASE_URL"));if(d){if(e.httpOptions){e.httpOptions.baseUrl=d}else{e.httpOptions={baseUrl:d}}}this.apiVersion=e.apiVersion;this.httpOptions=e.httpOptions;const f=new Ia({apiKey:this.apiKey,googleAuthOptions:e.googleAuthOptions});this.apiClient=new aa({auth:f,project:this.project,location:this.location,apiVersion:this.apiVersion,apiKey:this.apiKey,vertexai:this.vertexai,httpOptions:this.httpOptions,userAgentExtra:mS+process.version,uploader:new ka,downloader:new wa});this.models=new pa(this.apiClient);this.live=new da(this.apiClient,f,new Ra);this.batches=new js(this.apiClient);this.chats=new ta(this.models,this.apiClient);this.caches=new ea(this.apiClient);this.files=new xa(this.apiClient);this.operations=new ha(this.apiClient);this.authTokens=new ga(this.apiClient);this.tunings=new Ma(this.apiClient);this.fileSearchStores=new ya(this.apiClient)}};function Et(t){var e,n,i;return(i=(n=(e=process===null||process===void 0?void 0:process.env)===null||e===void 0?void 0:e[t])===null||n===void 0?void 0:n.trim())!==null&&i!==void 0?i:void 0}function ff(t){if(t===void 0){return false}return t.toLowerCase()==="true"}function ES(){const t=Et("GOOGLE_API_KEY");const e=Et("GEMINI_API_KEY");if(t&&e){console.warn("Both GOOGLE_API_KEY and GEMINI_API_KEY are set. Using GOOGLE_API_KEY.")}return t||e||void 0}function ew(t){return t.thought===true}function tw(t,e){if(typeof e==="string"&&e.length>0)return e;return t}var _S=/^[A-Za-z0-9+/]+={0,2}$/;function TS(t){if(!t)return false;if(t.length%4!==0)return false;return _S.test(t)}function Ha(t,e){return t&&TS(e)?e:void 0}function Va(t){return t.startsWith("claude-")||t.startsWith("gpt-oss-")}function AS(t){const e=t.toLowerCase().match(/^gemini(?:-live)?-(\d+)/);if(!e)return void 0;return Number.parseInt(e[1],10)}function CS(t){const e=AS(t);if(e!==void 0){return e>=3}return true}function nw(t,e){const n=[];const i=o=>{if(!Va(t.id))return o;return o.replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,64)};const r=Ja(e.messages,t,i);for(const o of r){if(o.role==="user"){if(typeof o.content==="string"){n.push({role:"user",parts:[{text:vt(o.content)}]})}else{const l=o.content.map(u=>{if(u.type==="text"){return{text:vt(u.text)}}else{return{inlineData:{mimeType:u.mimeType,data:u.data}}}});if(l.length===0)continue;n.push({role:"user",parts:l})}}else if(o.role==="assistant"){const l=[];const u=o.provider===t.provider&&o.model===t.id;for(const c of o.content){if(c.type==="text"){if(!c.text||c.text.trim()==="")continue;const d=Ha(u,c.textSignature);l.push({text:vt(c.text),...d&&{thoughtSignature:d}})}else if(c.type==="thinking"){if(!c.thinking||c.thinking.trim()==="")continue;if(u){const d=Ha(u,c.thinkingSignature);l.push({thought:true,text:vt(c.thinking),...d&&{thoughtSignature:d}})}else{l.push({text:vt(c.thinking)})}}else if(c.type==="toolCall"){const d=Ha(u,c.thoughtSignature);const f={functionCall:{name:c.name,args:c.arguments??{},...Va(t.id)?{id:c.id}:{}},...d&&{thoughtSignature:d}};l.push(f)}}if(l.length===0)continue;n.push({role:"model",parts:l})}else if(o.role==="toolResult"){const l=o.content.filter(v=>v.type==="text");const u=l.map(v=>v.text).join("\n");const c=t.input.includes("image")?o.content.filter(v=>v.type==="image"):[];const d=u.length>0;const f=c.length>0;const p=CS(t.id);const h=d?vt(u):f?"(see attached image)":"";const m=c.map(v=>({inlineData:{mimeType:v.mimeType,data:v.data}}));const _=Va(t.id);const A={functionResponse:{name:o.toolName,response:o.isError?{error:h}:{output:h},...f&&p&&{parts:m},..._?{id:o.toolCallId}:{}}};const T=n[n.length-1];if(T?.role==="user"&&T.parts?.some(v=>v.functionResponse)){T.parts.push(A)}else{n.push({role:"user",parts:[A]})}if(f&&!p){n.push({role:"user",parts:[{text:"Tool result image:"},...m]})}}}return n}var vS=new Set(["$schema","$id","$anchor","$dynamicAnchor","$vocabulary","$comment","$defs","definitions"]);function jf(t){if(typeof t!=="object"||t===null||Array.isArray(t)){return t}const e={};for(const[n,i]of Object.entries(t)){if(vS.has(n))continue;e[n]=jf(i)}return e}function iw(t,e=false){if(t.length===0)return void 0;return[{functionDeclarations:t.map(n=>({name:n.name,description:n.description,...e?{parameters:jf(n.parameters)}:{parametersJsonSchema:n.parameters}}))}]}function rw(t){switch(t){case"auto":return kt.AUTO;case"none":return kt.NONE;case"any":return kt.ANY;default:return kt.AUTO}}function ow(t){switch(t){case fe.STOP:return"stop";case fe.MAX_TOKENS:return"length";case fe.BLOCKLIST:case fe.PROHIBITED_CONTENT:case fe.SPII:case fe.SAFETY:case fe.IMAGE_SAFETY:case fe.IMAGE_PROHIBITED_CONTENT:case fe.IMAGE_RECITATION:case fe.IMAGE_OTHER:case fe.RECITATION:case fe.FINISH_REASON_UNSPECIFIED:case fe.OTHER:case fe.LANGUAGE:case fe.MALFORMED_FUNCTION_CALL:case fe.UNEXPECTED_TOOL_CALL:case fe.NO_IMAGE:return"error";default:{const e=t;throw new Error(`Unhandled stop reason: ${e}`)}}}export{$c as a,Us as b,df as c,ew as d,tw as e,nw as f,iw as g,rw as h,ow as i};
18
+ /*! Bundled license information:
19
+
20
+ @google/genai/dist/node/index.mjs:
21
+ @google/genai/dist/node/index.mjs:
22
+ @google/genai/dist/node/index.mjs:
23
+ @google/genai/dist/node/index.mjs:
24
+ @google/genai/dist/node/index.mjs:
25
+ (**
26
+ * @license
27
+ * Copyright 2025 Google LLC
28
+ * SPDX-License-Identifier: Apache-2.0
29
+ *)
30
+ */